任何应用程序都是从main()开始的,Flutter也不例外。Flutter 的启动入口在 lib/main.dart 里的 main() 函数中,代码如下。
void main() => runApp(MyApp());void runApp(Widget app) {final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();assert(binding.debugCheckZone('runApp'));binding..scheduleAttachRootWidget(binding.wrapWithDefaultView(app))..scheduleWarmUpFrame();
}
runApp的代码很简单,传递一个Widget参数,然后执行了三行代码,三行代码代表了Flutter App启动的主要三个流程:
- Binding初始化(ensureInitialized)
- 绑定根节点(scheduleAttachRootWidget)
- 绘制热身帧(scheduleWarmUpFrame)
接下来,我们就按照上面的流程来分析下Flutter App的启动流程。
Binding初始化
WidgetsFlutterBinding的源码比较简单,如下所示。
class WidgetsFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding {static Widg