Flutter圈子FlutterFlutter中文社区

Flutter是如何在iOS上运行起来的源码解读

2020-04-30  本文已影响0人  稻子_Aadan

摘要

本文主要是针对 Flutter 在 iOS 上是如何运行起来的源码进行串联,总结大致的运行流程。

涉及到的关键类有以下几个:

FlutterViewController

Flutter 嵌入原生应用必须有个载体,从这个点入手,在 Flutter Engine 源码中的 API 的入口点是 FlutterViewController,对其头文件源码做精简,大致如下

@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 有两个构造函数,本质上是一样的,第一个构造函数是谷歌为了在存在多个 FlutterViewController 的场景下为了让使用者能复用 FlutterEngine 而开放的。

- (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;
}

在构造函数中主要做了这么几件事情:

第二个构造函数中还多了这行代码,第一个构造函数把这个调用延后了而已

    [_engine.get() createShell:nil libraryURI:nil];

FlutterViewController 的 loadView

loadView 函数中,设置了 FlutterViewControllerview,并判断是否需要加载闪屏页,可以通过重写 splashScreenView 的 get 方法返回 nil 的方式彻底不加载闪屏页

- (void)loadView {
  self.view = _flutterView.get();
  self.view.multipleTouchEnabled = YES;
  self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

  [self installSplashScreenViewIfNecessary];
}

FlutterViewController 对 Navigator 的操作

FlutterViewController 提供了三个接口允许我们在原生端对 dart 的 Navigator 直接进行操作

- (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

setInitialRoute 在 iOS 端通过 navigationChannel 来告诉 dart 具体的 initialRoute,这个过程略微特殊,并不会在 dart 端直接接收 channel 信息,
而是在引擎层面做了处理,web_ui 不在本文的解析范畴,这里直接洗跟原生相关的点

setInitialRoute 设置流程如下:

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 端获取该值的流程。

pushRoute and popRoute

实现方式主要还是通过引擎内置的 navigationChannel 通知 dart 端,对应的在 dart 端 SystemChannels 类中,存在对应的 channel

static const MethodChannel navigation = MethodChannel(
      'flutter/navigation',
      JSONMethodCodec(),
  );

最终处理 pushRoutepopRoute 的逻辑在 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

FlutterView 并没有太多功能,主要是两点:

@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

FlutterEngine 对外暴露的接口不算多,主要就这么几点

我们主要关心引擎的构造、启动、释放和 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 的构造

FlutterEngine在构造时,要关注的有几下两点:

- (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 层面,需要关注以下一些类:

FlutterEngine 的启动,主要是两个事情

- (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
  if ([self createShell:entrypoint libraryURI:libraryURI]) {
    [self launchEngine:entrypoint libraryURI:libraryURI];
  }

  return _shell != nullptr;
}

createShell

createShell 的源码比较多,做了下精简,主要是以下几点:

- (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

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;
}

DartIsolate

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 做了什么

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 端找到对应的函数

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 之上,从源码层面看,有以下几点收获:

Flutter 运行流程

对整个 Flutter 运行的流程可以大致总结如下,主要是侧重在引擎侧,dart 那边的流程不展开,仅供参考:

作者其它文章

Flutter 在哈啰出行 B 端创新业务的实践

如何无缝的将Flutter引入现有应用?

上一篇下一篇

猜你喜欢

热点阅读