温故知新-runApp

48 阅读1分钟

runApp

Flutter项目的入口函数,入参是Widget,也就是我们的整个项目。

void runApp(Widget app) {
  final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
  //_runWidget(binding.wrapWithDefaultView(app), binding, 'runApp');
  binding
    ..scheduleAttachRootWidget(binding.wrapWithDefaultView(app))
    ..scheduleWarmUpFrame();
}

在开始查看binding之前,我们需要了解FlutterView和PlatformDispatcher有什么作用;

  1. FlutterView:
    可以理解会绘制当前窗口的画布,类似iOS的UIView,每个窗口对应一个FlutterView,每一个FlutterView都有自己的layer tree,每次调用[render]时都会渲染该layer tree。通过PlatformDispatcher去引用FlutterView,Flutter是通过系统的_addView(hooks.dart)创建,并保存在PlatformDispatcher单例的_views中。
  2. PlatformDispatcher:
    这是一个单例,是Flutter与操作系统的接口,是一个桥梁,它包含了核心调度Api、输入事件回调、图形绘制Api等等核心服务;
    PlatformDispatcher中定义了很多与操作系统之间交互的方法与回调,比如 _onViewFocusChange_beginFrame_onPointerDataPacket_onMetricsChanged_drawFrame等等,看到这些方法与回调函数的名称基本也可以猜到它们是做什么的,在阅读binding源码时也不会一脸懵。

WidgetsFlutterBinding

这个方式初始化各种服务,包括手势、渲染、语义、调度、绘制等服务;
# 温故知新-GestureBinding
# 温故知新-SchedulerBinding
# 温故知新-RendererBinding
# 温故知新-WidgetsBinding