本文主要是针对 Flutter 在 iOS 上是如何运行起来的源码进行串联,总结大体的运行流程。c++
涉及到的关键类有如下几个:git
Flutter 嵌入原生应用必须有个载体,从这个点入手,在 Flutter Engine 源码中的 API 的入口点是 FlutterViewController
,对其头文件源码作精简,大体以下github
@interface FlutterViewController : UIViewController <FlutterTextureRegistry, FlutterPluginRegistry> - (instancetype)initWithEngine:(FlutterEngine*)engine nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; - (instancetype)initWithProject:(nullable FlutterDartProject*)project nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; - (void)handleStatusBarTouches:(UIEvent*)event; - (void)setFlutterViewDidRenderCallback:(void (^)(void))callback; - (NSString*)lookupKeyForAsset:(NSString*)asset; - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package; - (void)setInitialRoute:(NSString*)route; - (void)popRoute; - (void)pushRoute:(NSString*)route; - (id<FlutterPluginRegistry>)pluginRegistry; @property(nonatomic, readonly, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI; @property(strong, nonatomic) UIView* splashScreenView; - (BOOL)loadDefaultSplashScreenView; @property(nonatomic, getter=isViewOpaque) BOOL viewOpaque; @property(weak, nonatomic, readonly) FlutterEngine* engine; @property(nonatomic, readonly) NSObject<FlutterBinaryMessenger>* binaryMessenger; @end
FlutterViewController 有两个构造函数,本质上是同样的,第一个构造函数是谷歌为了在存在多个 FlutterViewController
的场景下为了让使用者能复用 FlutterEngine
而开放的。web
- (instancetype)initWithEngine:(FlutterEngine*)engine nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle { NSAssert(engine != nil, @"Engine is required"); self = [super initWithNibName:nibName bundle:nibBundle]; if (self) { _viewOpaque = YES; _engine.reset([engine retain]); _engineNeedsLaunch = NO; _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine opaque:self.isViewOpaque]); _weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterViewController>>(self); _ongoingTouches = [[NSMutableSet alloc] init]; [self performCommonViewControllerInitialization]; [engine setViewController:self]; } return self; } - (instancetype)initWithProject:(nullable FlutterDartProject*)project nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle { self = [super initWithNibName:nibName bundle:nibBundle]; if (self) { _viewOpaque = YES; _weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterViewController>>(self); _engine.reset([[FlutterEngine alloc] initWithName:@"io.flutter" project:project allowHeadlessExecution:NO]); _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine opaque:self.isViewOpaque]); [_engine.get() createShell:nil libraryURI:nil]; _engineNeedsLaunch = YES; _ongoingTouches = [[NSMutableSet alloc] init]; [self loadDefaultSplashScreenView]; [self performCommonViewControllerInitialization]; } return self; }
在构造函数中主要作了这么几件事情:shell
FlutterEngine
FlutterView
FlutterEngine
的构造函数没有这项,应该是考虑了多 FlutterViewController
的场景下很差频繁加载闪屏页UIInterfaceOrientationMask
和 UIStatusBarStyle
Application
的生命周期,键盘事件,Accessibility
的事件等FlutterViewController
设置给 FlutterEngine
第二个构造函数中还多了这行代码,第一个构造函数把这个调用延后了而已json
[_engine.get() createShell:nil libraryURI:nil];
在 loadView
函数中,设置了 FlutterViewController
的 view
,并判断是否须要加载闪屏页,能够经过重写 splashScreenView
的 get 方法返回 nil
的方式完全不加载闪屏页segmentfault
- (void)loadView { self.view = _flutterView.get(); self.view.multipleTouchEnabled = YES; self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self installSplashScreenViewIfNecessary]; }
FlutterViewController
提供了三个接口容许咱们在原生端对 dart 的 Navigator
直接进行操做api
- (void)setInitialRoute:(NSString*)route { [[_engine.get() navigationChannel] invokeMethod:@"setInitialRoute" arguments:route]; } - (void)popRoute { [[_engine.get() navigationChannel] invokeMethod:@"popRoute" arguments:nil]; } - (void)pushRoute:(NSString*)route { [[_engine.get() navigationChannel] invokeMethod:@"pushRoute" arguments:route]; }
setInitialRoute
在 iOS 端经过 navigationChannel
来告诉 dart 具体的 initialRoute,这个过程略微特殊,并不会在 dart 端直接接收 channel 信息,
而是在引擎层面作了处理,web_ui 不在本文的解析范畴,这里直接洗跟原生相关的点app
setInitialRoute
设置流程以下:less
DispatchPlatformMessage
-> HandleNavigationPlatformMessage
-> initial_route_
void Engine::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) { if (message->channel() == kLifecycleChannel) { if (HandleLifecyclePlatformMessage(message.get())) return; } else if (message->channel() == kLocalizationChannel) { if (HandleLocalizationPlatformMessage(message.get())) return; } else if (message->channel() == kSettingsChannel) { HandleSettingsPlatformMessage(message.get()); return; } if (runtime_controller_->IsRootIsolateRunning() && runtime_controller_->DispatchPlatformMessage(std::move(message))) { return; } // If there's no runtime_, we may still need to set the initial route. if (message->channel() == kNavigationChannel) { HandleNavigationPlatformMessage(std::move(message)); return; } FML_DLOG(WARNING) << "Dropping platform message on channel: " << message->channel(); }
bool Engine::HandleNavigationPlatformMessage( fml::RefPtr<PlatformMessage> message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.data()), data.size()); if (document.HasParseError() || !document.IsObject()) return false; auto root = document.GetObject(); auto method = root.FindMember("method"); if (method->value != "setInitialRoute") return false; auto route = root.FindMember("args"); initial_route_ = std::move(route->value.GetString()); return true; }
setInitialRoute
最终在 HandleNavigationPlatformMessage
函数中直接被赋值给 initial_route_
。
setInitialRoute
读取流程以下:
Window.defaultRouteName
-> DefaultRouteName
-> Engine::DefaultRouteName
-> initial_route_
能够看到,关键字 native
,这是 dart 为了方便绑定 C/C++ 导出方法而添加的关键字,对应的 key 是 Window_defaultRouteName
class Window { String get defaultRouteName => _defaultRouteName(); String _defaultRouteName() native 'Window_defaultRouteName'; }
能够找到在引擎层的 flutter 命名空间下,有下面这个函数,注册了对应的导出函数,这里对应的是 DefaultRouteName
void Window::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({ {"Window_defaultRouteName", DefaultRouteName, 1, true}, {"Window_scheduleFrame", ScheduleFrame, 1, true}, {"Window_sendPlatformMessage", _SendPlatformMessage, 4, true}, {"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true}, {"Window_render", Render, 2, true}, {"Window_updateSemantics", UpdateSemantics, 2, true}, {"Window_setIsolateDebugName", SetIsolateDebugName, 2, true}, {"Window_reportUnhandledException", ReportUnhandledException, 2, true}, {"Window_setNeedsReportTimings", SetNeedsReportTimings, 2, true}, }); }
void DefaultRouteName(Dart_NativeArguments args) { std::string routeName = UIDartState::Current()->window()->client()->DefaultRouteName(); Dart_SetReturnValue(args, tonic::StdStringToDart(routeName)); }
再往下就是到 engine.cc 文件下面的函数,读取 initial_route_
的值
std::string Engine::DefaultRouteName() { if (!initial_route_.empty()) { return initial_route_; } return "/"; }
至此,完成了在原生端设置 defaultRouteName,在 dart 端获取该值的流程。
实现方式主要仍是经过引擎内置的 navigationChannel
通知 dart 端,对应的在 dart 端 SystemChannels
类中,存在对应的 channel
static const MethodChannel navigation = MethodChannel( 'flutter/navigation', JSONMethodCodec(), );
最终处理 pushRoute
和 popRoute
的逻辑在 WidgetsBinding
类中,主要是如下几个函数
Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) { switch (methodCall.method) { case 'popRoute': return handlePopRoute(); case 'pushRoute': return handlePushRoute(methodCall.arguments as String); } return Future<dynamic>.value(); } Future<void> handlePushRoute(String route) async { for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.from(_observers)) { if (await observer.didPushRoute(route)) return; } } Future<void> handlePopRoute() async { for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.from(_observers)) { if (await observer.didPopRoute()) return; } SystemNavigator.pop(); }
这段代码表示只有调用的方法返回 true
时才中断,每一个 handle 函数具体的处理逻辑是经过某个 WidgetsBindingObserver
来实现了,继续跟进找到以下代码
class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver { @override Future<bool> didPopRoute() async { assert(mounted); final NavigatorState navigator = _navigator?.currentState; if (navigator == null) return false; return await navigator.maybePop(); } @override Future<bool> didPushRoute(String route) async { assert(mounted); final NavigatorState navigator = _navigator?.currentState; if (navigator == null) return false; navigator.pushNamed(route); return true; } }
handlePopRoute
函数中,若是没有任何一个 observer
返回 true
,则最终调用 SystemNavigator.pop();
来退出应用程序
class SystemNavigator { static Future<void> pop({bool animated}) async { await SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop', animated); } }
FlutterView
并无太多功能,主要是两点:
FlutterViewEngineDelegate
flutter::IOSSurface
@protocol FlutterViewEngineDelegate <NSObject> - (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type asBase64Encoded:(BOOL)base64Encode; - (flutter::FlutterPlatformViewsController*)platformViewsController; @end @interface FlutterView : UIView - (instancetype)initWithDelegate:(id<FlutterViewEngineDelegate>)delegate opaque:(BOOL)opaque NS_DESIGNATED_INITIALIZER; - (std::unique_ptr<flutter::IOSSurface>)createSurface: (std::shared_ptr<flutter::IOSGLContext>)context; @end
takeScreenshot:asBase64Encoded:
应该是 FlutterView
渲染的数据源,具体参考 drawLayer:inContext:
的源码
@implementation FlutterView - (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context { if (layer != self.layer || context == nullptr) { return; } auto screenshot = [_delegate takeScreenshot:flutter::Rasterizer::ScreenshotType::UncompressedImage asBase64Encoded:NO]; if (!screenshot.data || screenshot.data->isEmpty() || screenshot.frame_size.isEmpty()) { return; } NSData* data = [NSData dataWithBytes:const_cast<void*>(screenshot.data->data()) length:screenshot.data->size()]; fml::CFRef<CGDataProviderRef> image_data_provider( CGDataProviderCreateWithCFData(reinterpret_cast<CFDataRef>(data))); fml::CFRef<CGColorSpaceRef> colorspace(CGColorSpaceCreateDeviceRGB()); fml::CFRef<CGImageRef> image(CGImageCreate( screenshot.frame_size.width(), // size_t width screenshot.frame_size.height(), // size_t height 8, // size_t bitsPerComponent 32, // size_t bitsPerPixel, 4 * screenshot.frame_size.width(), // size_t bytesPerRow colorspace, // CGColorSpaceRef space static_cast<CGBitmapInfo>(kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big), // CGBitmapInfo bitmapInfo image_data_provider, // CGDataProviderRef provider nullptr, // const CGFloat* decode false, // bool shouldInterpolate kCGRenderingIntentDefault // CGColorRenderingIntent intent )); const CGRect frame_rect = CGRectMake(0.0, 0.0, screenshot.frame_size.width(), screenshot.frame_size.height()); CGContextSaveGState(context); CGContextTranslateCTM(context, 0.0, CGBitmapContextGetHeight(context)); CGContextScaleCTM(context, 1.0, -1.0); CGContextDrawImage(context, frame_rect, image); CGContextRestoreGState(context); } @end
后面咱们会看到 FlutterViewEngineDelegate
其实是被 FlutterEngine
实现了。
这里不对 IOSSurface
作过多解析,其是创建在三种 layer 之上的,能够在编译期选择使用何种渲染方式
+ (Class)layerClass { #if TARGET_IPHONE_SIMULATOR return [CALayer class]; #else // TARGET_IPHONE_SIMULATOR #if FLUTTER_SHELL_ENABLE_METAL return [CAMetalLayer class]; #else // FLUTTER_SHELL_ENABLE_METAL return [CAEAGLLayer class]; #endif // FLUTTER_SHELL_ENABLE_METAL #endif // TARGET_IPHONE_SIMULATOR }
在 createSurface
函数中主要是分别建立三种对应的 IOSSurface
CALayer -> IOSSurfaceSoftware
CAEAGLLayer -> IOSSurfaceGL
CAMetalLayer -> IOSSurfaceMetal
再往下的渲染实际上就要交给 FlutterEngine
自身了。
FlutterEngine
对外暴露的接口不算多,主要就这么几点
initWithName:project:allowHeadlessExecution
,allowHeadlessExecution容许初始化引擎时不强依赖
FlutterViewController`runWithEntrypoint:libraryURI:
可传入自定义的 entrypoint
destroyContext
ensureSemanticsEnabled
,关于语义树文档比较少,大概是残疾人模式下须要用到的东西FlutterViewController
的 get/set咱们主要关心引擎的构造、启动、释放和 FlutterViewController
就差很少了,FlutterTextureRegistry
, FlutterPluginRegistry
不在本文关注范围内
@interface FlutterEngine : NSObject <FlutterTextureRegistry, FlutterPluginRegistry> - (instancetype)initWithName:(NSString*)labelPrefix project:(nullable FlutterDartProject*)project allowHeadlessExecution:(BOOL)allowHeadlessExecution NS_DESIGNATED_INITIALIZER; - (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint libraryURI:(nullable NSString*)uri; - (void)destroyContext; - (void)ensureSemanticsEnabled; @property(nonatomic, weak) FlutterViewController* viewController; @property(nonatomic, readonly, nullable) FlutterMethodChannel* localizationChannel; @property(nonatomic, readonly) FlutterMethodChannel* navigationChannel; @property(nonatomic, readonly) FlutterMethodChannel* platformChannel; @property(nonatomic, readonly) FlutterMethodChannel* textInputChannel; @property(nonatomic, readonly) FlutterBasicMessageChannel* lifecycleChannel; @property(nonatomic, readonly) FlutterBasicMessageChannel* systemChannel; @property(nonatomic, readonly) FlutterBasicMessageChannel* settingsChannel; @property(nonatomic, readonly) NSObject<FlutterBinaryMessenger>* binaryMessenger; @property(nonatomic, readonly, copy, nullable) NSString* isolateId; @end
FlutterEngine
在构造时,要关注的有几下两点:
FlutterDartProject
初始化FlutterPlatformViewsController
的初始化- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project allowHeadlessExecution:(BOOL)allowHeadlessExecution { self = [super init]; NSAssert(self, @"Super init cannot be nil"); NSAssert(labelPrefix, @"labelPrefix is required"); _allowHeadlessExecution = allowHeadlessExecution; _labelPrefix = [labelPrefix copy]; _weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterEngine>>(self); if (project == nil) _dartProject.reset([[FlutterDartProject alloc] init]); else _dartProject.reset([project retain]); _pluginPublications = [NSMutableDictionary new]; _platformViewsController.reset(new flutter::FlutterPlatformViewsController()); _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self]; NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(onMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; return self; }
FlutterEngine
层面,须要关注如下一些类:
FlutterEngine
的启动,主要是两个事情
- (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI { if ([self createShell:entrypoint libraryURI:libraryURI]) { [self launchEngine:entrypoint libraryURI:libraryURI]; } return _shell != nullptr; }
createShell
的源码比较多,作了下精简,主要是如下几点:
MessageLoop
ThreadHost
on_create_platform_view
回调on_create_rasterizer
回调flutter::TaskRunners
,若是开启 embedded_views_preview
则 使用当前线程的 TaskRunner
做为 gpu 线程的 TaskRunner
shell
,最终是启动 IsolateFlutterPlatformViewsController
FlutterObservatoryPublisher
PlatformView
channels- (BOOL)createShell:(NSString*)entrypoint libraryURI:(NSString*)libraryURI { // …… fml::MessageLoop::EnsureInitializedForCurrentThread(); _threadHost = {threadLabel.UTF8String, flutter::ThreadHost::Type::UI | flutter::ThreadHost::Type::GPU | flutter::ThreadHost::Type::IO}; flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view = [](flutter::Shell& shell) { return std::make_unique<flutter::PlatformViewIOS>(shell, shell.GetTaskRunners()); }; flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer = [](flutter::Shell& shell) { return std::make_unique<flutter::Rasterizer>(shell, shell.GetTaskRunners()); }; if (flutter::IsIosEmbeddedViewsPreviewEnabled()) { flutter::TaskRunners task_runners(threadLabel.UTF8String, // label fml::MessageLoop::GetCurrent().GetTaskRunner(), // platform fml::MessageLoop::GetCurrent().GetTaskRunner(), // gpu _threadHost.ui_thread->GetTaskRunner(), // ui _threadHost.io_thread->GetTaskRunner() // io ); // Create the shell. This is a blocking operation. _shell = flutter::Shell::Create(std::move(task_runners), // task runners std::move(settings), // settings on_create_platform_view, // platform view creation on_create_rasterizer // rasterzier creation ); } else { flutter::TaskRunners task_runners(threadLabel.UTF8String, // label fml::MessageLoop::GetCurrent().GetTaskRunner(), // platform _threadHost.gpu_thread->GetTaskRunner(), // gpu _threadHost.ui_thread->GetTaskRunner(), // ui _threadHost.io_thread->GetTaskRunner() // io ); // Create the shell. This is a blocking operation. _shell = flutter::Shell::Create(std::move(task_runners), // task runners std::move(settings), // settings on_create_platform_view, // platform view creation on_create_rasterizer // rasterzier creation ); } if (_shell != nullptr) { [self setupChannels]; if (!_platformViewsController) { _platformViewsController.reset(new flutter::FlutterPlatformViewsController()); } _publisher.reset([[FlutterObservatoryPublisher alloc] init]); [self maybeSetupPlatformViewChannels]; } return _shell != nullptr; }
这里能够看到会启动四个 TaskRunner
,分别为 platform,gpu, ui,io,但实际上并不必定对应四个线程。
launchEngine
实际上仍是在 shell
上进行的操做
- (void)launchEngine:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil { // Launch the Dart application with the inferred run configuration. self.shell.RunEngine([_dartProject.get() runConfigurationForEntrypoint:entrypoint libraryOrNil:libraryOrNil]); }
void Shell::RunEngine(RunConfiguration run_configuration) { RunEngine(std::move(run_configuration), nullptr); } void Shell::RunEngine(RunConfiguration run_configuration, std::function<void(Engine::RunStatus)> result_callback) { auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(), result_callback](Engine::RunStatus run_result) { if (!result_callback) { return; } platform_runner->PostTask( [result_callback, run_result]() { result_callback(run_result); }); }; FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { result(Engine::RunStatus::Failure); } fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), fml::MakeCopyable( [run_configuration = std::move(run_configuration), weak_engine = weak_engine_, result]() mutable { if (!weak_engine) { FML_LOG(ERROR) << "Could not launch engine with configuration - no engine."; result(Engine::RunStatus::Failure); return; } auto run_result = weak_engine->Run(std::move(run_configuration)); if (run_result == flutter::Engine::RunStatus::Failure) { FML_LOG(ERROR) << "Could not launch engine with configuration."; } result(run_result); })); }
再跟下去,最终会到[shell > common > engine.cc] 里面的 run
函数,最核心的是这行代码 PrepareAndLaunchIsolate
,最终整个流程跑下来就是为了启动 Isolate
Engine::RunStatus Engine::Run(RunConfiguration configuration) { if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return RunStatus::Failure; } auto isolate_launch_status = PrepareAndLaunchIsolate(std::move(configuration)); if (isolate_launch_status == Engine::RunStatus::Failure) { FML_LOG(ERROR) << "Engine not prepare and launch isolate."; return isolate_launch_status; } else if (isolate_launch_status == Engine::RunStatus::FailureAlreadyRunning) { return isolate_launch_status; } std::shared_ptr<DartIsolate> isolate = runtime_controller_->GetRootIsolate().lock(); bool isolate_running = isolate && isolate->GetPhase() == DartIsolate::Phase::Running; if (isolate_running) { tonic::DartState::Scope scope(isolate.get()); if (settings_.root_isolate_create_callback) { settings_.root_isolate_create_callback(); } if (settings_.root_isolate_shutdown_callback) { isolate->AddIsolateShutdownCallback( settings_.root_isolate_shutdown_callback); } std::string service_id = isolate->GetServiceId(); fml::RefPtr<PlatformMessage> service_id_message = fml::MakeRefCounted<flutter::PlatformMessage>( kIsolateChannel, std::vector<uint8_t>(service_id.begin(), service_id.end()), nullptr); HandlePlatformMessage(service_id_message); } return isolate_running ? Engine::RunStatus::Success : Engine::RunStatus::Failure; }
对 PrepareAndLaunchIsolate
函数作下精简,剩下两个点
Engine::RunStatus Engine::PrepareAndLaunchIsolate(RunConfiguration configuration) { // …… if (!isolate_configuration->PrepareIsolate(*isolate)) { return RunStatus::Failure; } if (!isolate->RunFromLibrary(configuration.GetEntrypointLibrary(), configuration.GetEntrypoint(), settings_.dart_entrypoint_args)) { return RunStatus::Failure; } return RunStatus::Success; }
主要看看 RunFromLibrary
作了什么
InvokeMainEntrypoint
bool DartIsolate::RunFromLibrary(const std::string& library_name, const std::string& entrypoint_name, const std::vector<std::string>& args, fml::closure on_run) { tonic::DartState::Scope scope(this); auto user_entrypoint_function = Dart_GetField(Dart_LookupLibrary(tonic::ToDart(library_name.c_str())), tonic::ToDart(entrypoint_name.c_str())); auto entrypoint_args = tonic::ToDart(args); if (!InvokeMainEntrypoint(user_entrypoint_function, entrypoint_args)) { return false; } phase_ = Phase::Running; if (on_run) { on_run(); } return true; }
再看看 InvokeMainEntrypoint
作了什么,源码作了精简,主要就这两步,咱们能够在 dart 端找到对应的函数
_getStartMainIsolateFunction
_runMainZoned
static bool InvokeMainEntrypoint(Dart_Handle user_entrypoint_function, Dart_Handle args) { Dart_Handle start_main_isolate_function = tonic::DartInvokeField(Dart_LookupLibrary(tonic::ToDart("dart:isolate")), "_getStartMainIsolateFunction", {}); if (tonic::LogIfError(tonic::DartInvokeField( Dart_LookupLibrary(tonic::ToDart("dart:ui")), "_runMainZoned", {start_main_isolate_function, user_entrypoint_function, args}))) { FML_LOG(ERROR) << "Could not invoke the main entrypoint."; return false; } return true; }
再往下就是 tonic 库,这是 fuchsia 下的库,谷歌并未开源到 github 上,但能够在这里看到 googlesource,后面可能会在其它文章中对 tonic 库进行梳理。
Flutter 运行于 iOS 之上,从源码层面看,有如下几点收获:
drawLayer
时会调用 takeScreenshot
来获取 Flutter 界面的光栅图TaskRunner
,Platform TaskRunner 不必定是独立的线程native
关键字调用 C/C++ 的函数,获取基本类型的数据返回值,性能比 channel 要好FlutterViewController
将全部的手势交互相关的都转发给 FlutterEngine对整个 Flutter 运行的流程能够大体总结以下,主要是侧重在引擎侧,dart 那边的流程不展开,仅供参考:
FlutterEngine
,传入 DartLibrary 和 EntrypointFlutterViewController
,FlutterView
FlutterEngine
的 viewController
做者其它文章