深入理解Flutter引擎启动

摘要

Flutter引擎启动源码详解。

Flutter技术架构概览

Flutter官方图分为三层,除了Framework、Engine、Embedder三层外,其实还有一层即我们在最上层编写的Dart代码。

Flutter System OverView

  1. Framework(Dart):用Dart编写,封装整个Flutter架构的核心功能,包括Widget、动画、绘制、手势等功能,有Material(Android风格UI)和Cupertino(iOS风格)的UI界面, 可构建Widget控件以及实现UI布局;
  2. Engine(C/C++):用C++编写,实现了Flutter的核心库,包括Dart虚拟机、动画和图形、文字渲染、通信通道、事件通知、插件架构等。引擎渲染采用的是2D图形渲染库Skia,虚拟机采用的是面向对象语言Dart VM,并将它们托管到平台的中间层代码(Embedder);
  3. Embedder(Platform Specific):嵌入层,为Engine创建和管理线程,作用是把Engine的Task Runners(任务运行器)运行在嵌入层管理的线程上。

实现 Embedder API 的叫做 shell ,shell实现了平台相关的代码,比如跟屏幕键盘IME和系统应用生命周期事件的交互。不同平台有不同的shell,比如Android和iOS的shell。

Flutter引擎启动[基于Flutter 1.17.5 分析]

这里以Android为例,APP启动过程,会执行Application和Activity的onCreate()方法,FlutterApplication和FlutterActivity的onCreate()方法正是连接Native和Flutter的枢纽。

  • FlutterApplication.java的onCreate过程主要完成初始化配置、加载引擎libflutter.so、注册JNI方法;
  • FlutterActivity.java的onCreate过程,通过FlutterJNI的AttachJNI()方法来初始化引擎Engine、Dart虚拟机、Isolate、taskRunner等对象。再经过层层处理最终调用main.dart中main()方法,执行runApp(Widget app)来处理整个Dart业务代码。

1.FlutterApplication启动

在AndrodManifest.xml定义的FlutterApplication,Android应用在启动时候会执行FlutterApplication.onCreate(),然后再执行FlutterMain.startInitialization()方法,其主要工作:

  1. 确保该方法必须运行在主线程,否则抛出异常;
  2. 初始化FlutterLoader的相关配置信息flutter_assets、vm_snapshot_data、isolate_snapshot_data等,当metadata数据没有配置初始值时则采用默认值;
  3. 文件清理、提取资源(例如应用根目录下的所有assets资源等)加载到内存,这个过程都是在异步线程执行完成;
  4. 加载libflutter.so库,无论是System.loadLibrary(),还是System.load()最终都会调用到该加载库中的JNI_OnLoad() -> flutter/shell/platform/android/library_loader.cc
    1. Android进程在由zygote fork过程中已创建了JavaVM,每一个进程对应一个JavaVM。在这里只是将当前进程的JavaVM实例保存在静态变量,再将当前线程和JavaVM建立关联,获取JNIEnv实例,每个线程对应一个JNIEnv实例 -> flutter/fml/platform/android/jni_util.cc
    2. 注册FlutterJNI的JNI方法,nativeInit()和nativeRecordStartTimestamp() -> flutter/shell/platform/android/flutter_main.cc
    3. 注册PlatformViewAndroid的一系列方法,完成Java和C++的一些方法互调 -> flutter/shell/platform/android/platform_view_android_jni.cc
      • 通过RegisterNatives()方法注册一些类的Native方法,用于Java调用C++的过程;
      • 通过GetMethodID()方法记录了一些类的Java方法的jmethodID,用于C++调用Java的过程;
    4. 注册FlutterJNI的nativeOnVsync()用于Java调用C++,asyncWaitForVsync()用于C++调用Java -> flutter/shell/platform/android/vsync_waiter_android.cc
  5. 最终通过engine_main_enter_ts变量记录FlutterApplication的启动耗时 -> flutter/shell/platform/android/flutter_main.cc

2.FlutterActivity启动

每一个FlutterActivity都会对应一个FlutterActivityAndFragmentDelegate代理类,FlutterActivity的工作全权委托给FlutterActivityAndFragmentDelegate类,包括onCreate(),onResume()等全部的生命周期回调方法。

2.1 FlutterActivity#onCreate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected void onCreate(@Nullable Bundle savedInstanceState) {
// 查看是否有配置主题
this.switchLaunchThemeForNormalTheme();
super.onCreate(savedInstanceState);
this.lifecycle.handleLifecycleEvent(Event.ON_CREATE);
// 初始化delegate
this.delegate = new FlutterActivityAndFragmentDelegate(this);
// 初始化Flutter Engine相关,接下来详细分析[见2.2]
this.delegate.onAttach(this);
// 恢复状态onRestoreInstanceState的调用
this.delegate.onActivityCreated(savedInstanceState);
// 当Intent配置的backgroundMode是透明时,就配置window透明
this.configureWindowForTransparency();
// 创建FlutterView,实际上是调用delegate#onCreateView,接下来详细分析[见2.3]
this.setContentView(this.createFlutterView());
this.configureStatusBarForFullscreenFlutterExperience();
}
protected void onStart() {
super.onStart();
this.lifecycle.handleLifecycleEvent(Event.ON_START);
// [见2.4]
this.delegate.onStart();
}

2.2 FlutterActivityAndFragmentDelegate#onAttach

  1. 当FlutterActivity复用时,Flutter Engine复用;否则初始化Flutter Engine[详见3],创建PlatformChannel、FlutterEnginePluginRegistry等对象
  2. 将Flutter Engine附加到FlutterActivity,以FlutterEnginePluginRegistry作为桥接媒介
  3. 调用io.flutter.plugins.GeneratedPluginRegistrant#registerWith方法,它是自动生成的类,与最上层我们写的Dart代码插件关联

2.3 FlutterActivityAndFragmentDelegate#onCreateView

  1. 创建FlutterView
  2. 给FlutterView添加第一帧绘制回调
  3. 创建FlutterSplashView,将FlutterView交给FlutterSplashView
    将FlutterView挂载到Engine

2.4 FlutterActivityAndFragmentDelegate#onStart

1
2
3
4
5
void onStart() {
Log.v("FlutterActivityAndFragmentDelegate", "onStart()");
this.ensureAlive();
this.doInitialFlutterViewRun();
}

2.4.0 doInitialFlutterViewRun

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void doInitialFlutterViewRun() {
if (this.host.getCachedEngineId() == null) {
if (!this.flutterEngine.getDartExecutor().isExecutingDart()) {
Log.v("FlutterActivityAndFragmentDelegate", "Executing Dart entrypoint: " + this.host.getDartEntrypointFunctionName() + ", and sending initial route: " + this.host.getInitialRoute());
if (this.host.getInitialRoute() != null) {
this.flutterEngine.getNavigationChannel().setInitialRoute(this.host.getInitialRoute());
}
DartEntrypoint entrypoint = new DartEntrypoint(this.host.getAppBundlePath(), this.host.getDartEntrypointFunctionName());
// 见[2.4.1]
this.flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint);
}
}
}

参数中的DartEntrypoint#dartEntrypointFunctionName代表主函数入口名,DartEntrypoint#pathToBundle代表对应库的路径,dartEntrypointFunctionName一般都等于”main”。

2.4.1 DartExecutor#executeDartEntrypoint

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// DartExecutor.java
public void executeDartEntrypoint(@NonNull DartExecutor.DartEntrypoint dartEntrypoint) {
if (this.isApplicationRunning) {
Log.w("DartExecutor", "Attempted to run a DartExecutor that is already running.");
} else {
Log.v("DartExecutor", "Executing Dart entrypoint: " + dartEntrypoint);
this.flutterJNI.runBundleAndSnapshotFromLibrary(dartEntrypoint.pathToBundle, dartEntrypoint.dartEntrypointFunctionName, (String)null, this.assetManager);
this.isApplicationRunning = true;
}
}
// FlutterJNI.java
public void runBundleAndSnapshotFromLibrary(@NonNull String bundlePath, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @NonNull AssetManager assetManager) {
this.ensureRunningOnMainThread();
this.ensureAttachedToNative();
// [见2.4.2]
this.nativeRunBundleAndSnapshotFromLibrary(this.nativePlatformViewId, bundlePath, entrypointFunctionName, pathToEntrypointFunction, assetManager);
}

2.4.2 nativeRunBundleAndSnapshotFromLibrary

该native方法在
-> flutter/shell/platform/android/platform_view_android_jni.cc中注册,对应方法名为”RunBundleAndSnapshotFromLibrary”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#define ANDROID_SHELL_HOLDER \
(reinterpret_cast<AndroidShellHolder*>(shell_holder))
static jlong AttachJNI(JNIEnv* env,
jclass clazz,
jobject flutterJNI,
jboolean is_background_view) {
fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
auto shell_holder = std::make_unique<AndroidShellHolder>(
FlutterMain::Get().GetSettings(), java_object, is_background_view);
if (shell_holder->IsValid()) {
return reinterpret_cast<jlong>(shell_holder.release());
} else {
return 0;
}
}
static void RunBundleAndSnapshotFromLibrary(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jstring jBundlePath,
jstring jEntrypoint,
jstring jLibraryUrl,
jobject jAssetManager) {
auto asset_manager = std::make_shared<flutter::AssetManager>();
asset_manager->PushBack(std::make_unique<flutter::APKAssetProvider>(
env, // jni environment
jAssetManager, // asset manager
fml::jni::JavaStringToString(env, jBundlePath)) // apk asset dir
);
std::unique_ptr<IsolateConfiguration> isolate_configuration;
if (flutter::DartVM::IsRunningPrecompiledCode()) {
isolate_configuration = IsolateConfiguration::CreateForAppSnapshot();
} else {
std::unique_ptr<fml::Mapping> kernel_blob =
fml::FileMapping::CreateReadOnly(
ANDROID_SHELL_HOLDER->GetSettings().application_kernel_asset);
if (!kernel_blob) {
FML_DLOG(ERROR) << "Unable to load the kernel blob asset.";
return;
}
isolate_configuration =
IsolateConfiguration::CreateForKernel(std::move(kernel_blob));
}
RunConfiguration config(std::move(isolate_configuration),
std::move(asset_manager));
{
auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint);
auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl);
if ((entrypoint.size() > 0) && (libraryUrl.size() > 0)) {
config.SetEntrypointAndLibrary(std::move(entrypoint),
std::move(libraryUrl));
} else if (entrypoint.size() > 0) {
config.SetEntrypoint(std::move(entrypoint));
}
}
// [见2.4.3]
ANDROID_SHELL_HOLDER->Launch(std::move(config));
}

2.4.3 ANDROID_SHELL_HOLDER->Launch

-> flutter/shell/platform/android/android_shell_holder.cc

1
2
3
4
5
6
7
void AndroidShellHolder::Launch(RunConfiguration config) {
if (!IsValid()) {
return;
}
// [见2.4.4]
shell_->RunEngine(std::move(config));
}

2.4.4 shell_->RunEngine

-> flutter/shell/common/shell.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
void Shell::RunEngine(RunConfiguration run_configuration) {
RunEngine(std::move(run_configuration), nullptr);
}
void Shell::RunEngine(
RunConfiguration run_configuration,
const 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());
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;
}
// [见2.4.5]
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);
}));
}

2.4.5 weak_engine->Run

-> flutter/shell/common/engine.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Engine::RunStatus Engine::Run(RunConfiguration configuration) {
if (!configuration.IsValid()) {
FML_LOG(ERROR) << "Engine run configuration was invalid.";
return RunStatus::Failure;
}
last_entry_point_ = configuration.GetEntrypoint();
last_entry_point_library_ = configuration.GetEntrypointLibrary();
// [见2.4.6]
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;
}

2.4.6 PrepareAndLaunchIsolate

-> flutter/shell/common/engine.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Engine::RunStatus Engine::PrepareAndLaunchIsolate(
RunConfiguration configuration) {
TRACE_EVENT0("flutter", "Engine::PrepareAndLaunchIsolate");
UpdateAssetManager(configuration.GetAssetManager());
auto isolate_configuration = configuration.TakeIsolateConfiguration();
std::shared_ptr<DartIsolate> isolate =
runtime_controller_->GetRootIsolate().lock();
if (!isolate) {
return RunStatus::Failure;
}
// This can happen on iOS after a plugin shows a native window and returns to
// the Flutter ViewController.
if (isolate->GetPhase() == DartIsolate::Phase::Running) {
FML_DLOG(WARNING) << "Isolate was already running!";
return RunStatus::FailureAlreadyRunning;
}
if (!isolate_configuration->PrepareIsolate(*isolate)) {
FML_LOG(ERROR) << "Could not prepare to run the isolate.";
return RunStatus::Failure;
}
if (configuration.GetEntrypointLibrary().empty()) {
// [见2.4.7]
if (!isolate->Run(configuration.GetEntrypoint(),
settings_.dart_entrypoint_args)) {
FML_LOG(ERROR) << "Could not run the isolate.";
return RunStatus::Failure;
}
} else {
if (!isolate->RunFromLibrary(configuration.GetEntrypointLibrary(),
configuration.GetEntrypoint(),
settings_.dart_entrypoint_args)) {
FML_LOG(ERROR) << "Could not run the isolate.";
return RunStatus::Failure;
}
}
return RunStatus::Success;
}

从configuration中获取主函数入口,RunConfiguration有一个成员变量entrypoint_值等于“main”, 还有一个成员变量entrypointlibrary,这两个变量赋值的过程[见2.4.0]。

2.4.7 isolate->Run

-> flutter/runtime/dart_isolate.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[[nodiscard]] bool DartIsolate::Run(const std::string& entrypoint_name,
const std::vector<std::string>& args,
const fml::closure& on_run) {
TRACE_EVENT0("flutter", "DartIsolate::Run");
if (phase_ != Phase::Ready) {
return false;
}
tonic::DartState::Scope scope(this);
// 获取用户入口函数,也就是主函数main
auto user_entrypoint_function =
Dart_GetField(Dart_RootLibrary(), tonic::ToDart(entrypoint_name.c_str()));
auto entrypoint_args = tonic::ToDart(args);
// [见2.4.8]
if (!InvokeMainEntrypoint(user_entrypoint_function, entrypoint_args)) {
return false;
}
phase_ = Phase::Running;
if (on_run) {
on_run();
}
return true;
}

2.4.8 InvokeMainEntrypoint

-> flutter/runtime/dart_isolate.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[[nodiscard]] static bool InvokeMainEntrypoint(
Dart_Handle user_entrypoint_function,
Dart_Handle args) {
if (tonic::LogIfError(user_entrypoint_function)) {
FML_LOG(ERROR) << "Could not resolve main entrypoint function.";
return false;
}
// [见2.4.9]
Dart_Handle start_main_isolate_function =
tonic::DartInvokeField(Dart_LookupLibrary(tonic::ToDart("dart:isolate")),
"_getStartMainIsolateFunction", {});
if (tonic::LogIfError(start_main_isolate_function)) {
FML_LOG(ERROR) << "Could not resolve main entrypoint trampoline.";
return false;
}
// [见2.4.10]
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;
}

经过Dart虚拟机最终会调用的Dart层的_runMainZoned()方法,其中参数start_main_isolate_function等于_startIsolate。

2.4.9 _getStartMainIsolateFunction

未完待续

2.4.10 _runMainZoned

未完待续

3.FlutterEngine初始化

3.1 FlutterActivityAndFragmentDelegate#onAttach

1
2
3
4
5
6
7
8
9
void onAttach(@NonNull Context context) {
...
if (this.flutterEngine == null) {
this.setupFlutterEngine();
}
...
}

3.2 FlutterActivityAndFragmentDelegate#setupFlutterEngine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void setupFlutterEngine() {
Log.v("FlutterActivityAndFragmentDelegate", "Setting up FlutterEngine.");
String cachedEngineId = this.host.getCachedEngineId();
// 取缓存的FlutterEngine
if (cachedEngineId != null) {
this.flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
this.isFlutterEngineFromHost = true;
if (this.flutterEngine == null) {
throw new IllegalStateException("The requested cached FlutterEngine did not exist in the FlutterEngineCache: '" + cachedEngineId + "'");
}
} else {
this.flutterEngine = this.host.provideFlutterEngine(this.host.getContext());
if (this.flutterEngine != null) {
this.isFlutterEngineFromHost = true;
} else {
Log.v("FlutterActivityAndFragmentDelegate", "No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterFragment.");
// FlutterEngine真正的初始化[见3.3]
this.flutterEngine = new FlutterEngine(this.host.getContext(), this.host.getFlutterShellArgs().toArray(), false);
this.isFlutterEngineFromHost = false;
}
}
}

3.3 FlutterEngine构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public FlutterEngine(@NonNull Context context, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) {
this(context, FlutterLoader.getInstance(), new FlutterJNI(), dartVmArgs, automaticallyRegisterPlugins);
}
// 最终调用到此处
public FlutterEngine(@NonNull Context context, @NonNull FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @NonNull PlatformViewsController platformViewsController, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) {
this.engineLifecycleListeners = new HashSet();
this.engineLifecycleListener = new FlutterEngine.EngineLifecycleListener() {
public void onPreEngineRestart() {
Log.v("FlutterEngine", "onPreEngineRestart()");
Iterator var1 = FlutterEngine.this.engineLifecycleListeners.iterator();
while(var1.hasNext()) {
FlutterEngine.EngineLifecycleListener lifecycleListener = (FlutterEngine.EngineLifecycleListener)var1.next();
lifecycleListener.onPreEngineRestart();
}
FlutterEngine.this.platformViewsController.onPreEngineRestart();
}
};
//上面构造方法new FlutterJNI()传进来的,nativeInit方法就在FlutterJNI里面
this.flutterJNI = flutterJNI;
// 回到FlutterLoader#startInitialization初始化方法,前面在分析<FlutterApplication启动>已经提到
flutterLoader.startInitialization(context.getApplicationContext());
// 确保初始化完成[见3.3.1]
flutterLoader.ensureInitializationComplete(context, dartVmArgs);
flutterJNI.addEngineLifecycleListener(this.engineLifecycleListener);
// [见3.3.2]
this.attachToJni();
...
if (automaticallyRegisterPlugins) {
this.registerPlugins();
}
}
3.3.1 flutterLoader.ensureInitializationComplete(context, dartVmArgs)

调用FlutterJNI#nativeInit,最终调用C++对应flutter_main.cc#FlutterMain::Init

3.3.2 this.attachToJni()
  1. 调用FlutterJNI#attachToNative->FlutterJNI#nativeAttach
    (在加载flutter.so时注册该方法,见flutter/shell/platform/android/platform_view_android_jni.cc)
  2. 调用C++对应platform_view_android_jni.cc#AttachJNI:为了在引擎层初始化AndroidShellHolder对象

3.4 AndroidShellHolder初始化

-> flutter/shell/platform/android/android_shell_holder.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
AndroidShellHolder::AndroidShellHolder(
flutter::Settings settings,
fml::jni::JavaObjectWeakGlobalRef java_object,
bool is_background_view)
: settings_(std::move(settings)), java_object_(java_object) {
static size_t shell_count = 1;
auto thread_label = std::to_string(shell_count++);
// 创建线程私有的key
FML_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==
0);
if (is_background_view) {
thread_host_ = {thread_label, ThreadHost::Type::UI};
} else {
// 创建目标线程[见3.5]
thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU | ThreadHost::Type::IO};
}
// Detach from JNI when the UI and raster threads exit.
// 当UI和GPU线程退出时从JNI分离
auto jni_exit_task([key = thread_destruct_key_]() {
FML_CHECK(pthread_setspecific(key, reinterpret_cast<void*>(1)) == 0);
});
thread_host_.ui_thread->GetTaskRunner()->PostTask(jni_exit_task);
if (!is_background_view) {
thread_host_.raster_thread->GetTaskRunner()->PostTask(jni_exit_task);
}
fml::WeakPtr<PlatformViewAndroid> weak_platform_view;
Shell::CreateCallback<PlatformView> on_create_platform_view =
[is_background_view, java_object, &weak_platform_view](Shell& shell) {
std::unique_ptr<PlatformViewAndroid> platform_view_android;
if (is_background_view) {
platform_view_android = std::make_unique<PlatformViewAndroid>(
shell, // delegate
shell.GetTaskRunners(), // task runners
java_object // java object handle for JNI interop
);
} else {
platform_view_android = std::make_unique<PlatformViewAndroid>(
shell, // delegate
shell.GetTaskRunners(), // task runners
java_object, // java object handle for JNI interop
shell.GetSettings()
.enable_software_rendering // use software rendering
);
}
weak_platform_view = platform_view_android->GetWeakPtr();
return platform_view_android;
};
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(shell, shell.GetTaskRunners());
};
// The current thread will be used as the platform thread. Ensure that the message loop is initialized.
// 把当前线程将用作平台线程,并确保为当前线程初始化MessageLoop
fml::MessageLoop::EnsureInitializedForCurrentThread();
fml::RefPtr<fml::TaskRunner> gpu_runner;
fml::RefPtr<fml::TaskRunner> ui_runner;
fml::RefPtr<fml::TaskRunner> io_runner;
fml::RefPtr<fml::TaskRunner> platform_runner =
fml::MessageLoop::GetCurrent().GetTaskRunner();
if (is_background_view) {
auto single_task_runner = thread_host_.ui_thread->GetTaskRunner();
gpu_runner = single_task_runner;
ui_runner = single_task_runner;
io_runner = single_task_runner;
} else {
gpu_runner = thread_host_.raster_thread->GetTaskRunner();
ui_runner = thread_host_.ui_thread->GetTaskRunner();
io_runner = thread_host_.io_thread->GetTaskRunner();
}
// 创建Task Runners对象
flutter::TaskRunners task_runners(thread_label, // label
platform_runner, // platform
gpu_runner, // raster
ui_runner, // ui
io_runner // io
);
// 创建Shell对象[见3.6]
shell_ =
Shell::Create(task_runners, // task runners
GetDefaultWindowData(), // window data
settings_, // settings
on_create_platform_view, // platform view create callback
on_create_rasterizer // rasterizer create callback
);
platform_view_ = weak_platform_view;
FML_DCHECK(platform_view_);
is_valid_ = shell_ != nullptr;
if (is_valid_) {
// 提升ui线程和gpu线程的优先级
task_runners.GetRasterTaskRunner()->PostTask([]() {
// Android describes -8 as "most important display threads, for
// compositing the screen and retrieving input events". Conservatively
// set the raster thread to slightly lower priority than it.
if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {
// Defensive fallback. Depending on the OEM, it may not be possible
// to set priority to -5.
if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {
FML_LOG(ERROR) << "Failed to set GPU task runner priority";
}
}
});
task_runners.GetUITaskRunner()->PostTask([]() {
if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {
FML_LOG(ERROR) << "Failed to set UI task runner priority";
}
});
}
}

该方法主要功能:

  1. 创建UI/GPU/IO三个线程,并为它们分别初始化MessageLoop、TaskRunner
  2. 创建TaskRunners对象 ->flutter/common/task_runners.cc
  3. on_create_platform_view
  4. on_create_rasterizer
  5. 创建Shell对象

3.5 ThreadHost初始化

-> flutter/shell/common/thread_host.cc

  1. 根据传递的参数,首次创建AndroidShellHolder实例的过程,会创建1.ui、1.gpu、1.io3个线程
  2. 每个线程Thread初始化过程 ->flutter/fml/thread.cc,都创建相应的MessageLoop ->flutter/fml/message_loop.cc、TaskRunner->flutter/fml/task_runner.cc对象,然后进入pollOnce轮询等待状态。

3.6 创建Shell

-> flutter/shell/common/shell.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
std::unique_ptr<Shell> Shell::Create(
TaskRunners task_runners,
const WindowData window_data,
Settings settings,
Shell::CreateCallback<PlatformView> on_create_platform_view,
Shell::CreateCallback<Rasterizer> on_create_rasterizer) {
// [见3.6.1]
PerformInitializationTasks(settings);
PersistentCache::SetCacheSkSL(settings.cache_sksl);
TRACE_EVENT0("flutter", "Shell::Create");
// [见3.6.2]
auto vm = DartVMRef::Create(settings);
FML_CHECK(vm) << "Must be able to initialize the VM.";
auto vm_data = vm->GetVMData();
// [见3.6.3]
return Shell::Create(std::move(task_runners), //
std::move(window_data), //
std::move(settings), //
vm_data->GetIsolateSnapshot(), // isolate snapshot
on_create_platform_view, //
on_create_rasterizer, //
std::move(vm) //
);
}
3.6.1 PerformInitializationTasks()

->flutter/shell/common/shell.cc

默认情况只有ERROR级别的日志才会输出,除非在启动的时候带上参数verbose_logging,则会打印出INFO级别的日志。

3.6.2 DartVMRef::Create

-> flutter/runtime/dart_vm_lifecycle.cc

  1. 当该进程存在一个正在运行的虚拟机,获取其强引用,复用该虚拟机

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // If there is already a running VM in the process, grab a strong reference to
    // it.
    if (auto vm = gVM.lock()) {
    FML_DLOG(WARNING) << "Attempted to create a VM in a process where one was "
    "already running. Ignoring arguments for current VM "
    "create call and reusing the old VM.";
    // There was already a running VM in the process,
    return DartVMRef{std::move(vm)};
    }
  2. 如果没有则创建虚拟机

3.6.3 Shell::Create

-> flutter/shell/common/shell.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
std::unique_ptr<Shell> Shell::Create(
TaskRunners task_runners,
const WindowData window_data,
Settings settings,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
const Shell::CreateCallback<PlatformView>& on_create_platform_view,
const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
DartVMRef vm) {
PerformInitializationTasks(settings);
PersistentCache::SetCacheSkSL(settings.cache_sksl);
TRACE_EVENT0("flutter", "Shell::CreateWithSnapshots");
if (!task_runners.IsValid() || !on_create_platform_view ||
!on_create_rasterizer) {
return nullptr;
}
fml::AutoResetWaitableEvent latch;
std::unique_ptr<Shell> shell;
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetPlatformTaskRunner(),
fml::MakeCopyable([&latch, //
vm = std::move(vm), //
&shell, //
task_runners = std::move(task_runners), //
window_data, //
settings, //
isolate_snapshot = std::move(isolate_snapshot), //
on_create_platform_view, //
on_create_rasterizer //
]() mutable {
// [见3.6.4]
shell = CreateShellOnPlatformThread(std::move(vm),
std::move(task_runners), //
window_data, //
settings, //
std::move(isolate_snapshot), //
on_create_platform_view, //
on_create_rasterizer //
);
latch.Signal();
}));
latch.Wait();
return shell;
}
3.6.4 CreateShellOnPlatformThread

-> flutter/shell/common/shell.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
std::unique_ptr<Shell> Shell::CreateShellOnPlatformThread(
DartVMRef vm,
TaskRunners task_runners,
const WindowData window_data,
Settings settings,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
const Shell::CreateCallback<PlatformView>& on_create_platform_view,
const Shell::CreateCallback<Rasterizer>& on_create_rasterizer) {
if (!task_runners.IsValid()) {
FML_LOG(ERROR) << "Task runners to run the shell were invalid.";
return nullptr;
}
// 创建Shell对象[见3.6.5]
auto shell =
std::unique_ptr<Shell>(new Shell(std::move(vm), task_runners, settings));
// Create the rasterizer on the raster thread.
std::promise<std::unique_ptr<Rasterizer>> rasterizer_promise;
auto rasterizer_future = rasterizer_promise.get_future();
std::promise<fml::WeakPtr<SnapshotDelegate>> snapshot_delegate_promise;
auto snapshot_delegate_future = snapshot_delegate_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetRasterTaskRunner(), [&rasterizer_promise, //
&snapshot_delegate_promise,
on_create_rasterizer, //
shell = shell.get() //
]() {
TRACE_EVENT0("flutter", "ShellSetupGPUSubsystem");
// 在GPU线程中创建rasterizer对象[见3.6.6]
std::unique_ptr<Rasterizer> rasterizer(on_create_rasterizer(*shell));
snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate());
rasterizer_promise.set_value(std::move(rasterizer));
});
// Create the platform view on the platform thread (this thread).
// 在主线程创建platform_view[见3.6.7]
auto platform_view = on_create_platform_view(*shell.get());
if (!platform_view || !platform_view->GetWeakPtr()) {
return nullptr;
}
// Ask the platform view for the vsync waiter. This will be used by the engine
// to create the animator.
// 由platform_view创建vsync waiter [见3.6.8]
auto vsync_waiter = platform_view->CreateVSyncWaiter();
if (!vsync_waiter) {
return nullptr;
}
// Create the IO manager on the IO thread. The IO manager must be initialized
// first because it has state that the other subsystems depend on. It must
// first be booted and the necessary references obtained to initialize the
// other subsystems.
std::promise<std::unique_ptr<ShellIOManager>> io_manager_promise;
auto io_manager_future = io_manager_promise.get_future();
std::promise<fml::WeakPtr<ShellIOManager>> weak_io_manager_promise;
auto weak_io_manager_future = weak_io_manager_promise.get_future();
std::promise<fml::RefPtr<SkiaUnrefQueue>> unref_queue_promise;
auto unref_queue_future = unref_queue_promise.get_future();
auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner();
// TODO(gw280): The WeakPtr here asserts that we are derefing it on the
// same thread as it was created on. We are currently on the IO thread
// inside this lambda but we need to deref the PlatformView, which was
// constructed on the platform thread.
//
// https://github.com/flutter/flutter/issues/42948
fml::TaskRunner::RunNowOrPostTask(
io_task_runner,
[&io_manager_promise, //
&weak_io_manager_promise, //
&unref_queue_promise, //
platform_view = platform_view->GetWeakPtr(), //
io_task_runner, //
is_backgrounded_sync_switch = shell->GetIsGpuDisabledSyncSwitch() //
]() {
TRACE_EVENT0("flutter", "ShellSetupIOSubsystem");
// 在IO线程中创建ShellIOManager对象[见3.6.9]
auto io_manager = std::make_unique<ShellIOManager>(
platform_view.getUnsafe()->CreateResourceContext(),
is_backgrounded_sync_switch, io_task_runner);
weak_io_manager_promise.set_value(io_manager->GetWeakPtr());
unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue());
io_manager_promise.set_value(std::move(io_manager));
});
// Send dispatcher_maker to the engine constructor because shell won't have
// platform_view set until Shell::Setup is called later.
auto dispatcher_maker = platform_view->GetDispatcherMaker();
// Create the engine on the UI thread.
std::promise<std::unique_ptr<Engine>> engine_promise;
auto engine_future = engine_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
fml::MakeCopyable([&engine_promise, //
shell = shell.get(), //
&dispatcher_maker, //
&window_data, //
isolate_snapshot = std::move(isolate_snapshot), //
vsync_waiter = std::move(vsync_waiter), //
&weak_io_manager_future, //
&snapshot_delegate_future, //
&unref_queue_future //
]() mutable {
TRACE_EVENT0("flutter", "ShellSetupUISubsystem");
const auto& task_runners = shell->GetTaskRunners();
// The animator is owned by the UI thread but it gets its vsync pulses
// from the platform.
// 创建Animator对象 [见3.6.10]
auto animator = std::make_unique<Animator>(*shell, task_runners,
std::move(vsync_waiter));
// 创建Engine对象 [见3.6.11]
engine_promise.set_value(std::make_unique<Engine>(
*shell, //
dispatcher_maker, //
*shell->GetDartVM(), //
std::move(isolate_snapshot), //
task_runners, //
window_data, //
shell->GetSettings(), //
std::move(animator), //
weak_io_manager_future.get(), //
unref_queue_future.get(), //
snapshot_delegate_future.get() //
));
}));
// [见3.6.12]
if (!shell->Setup(std::move(platform_view), //
engine_future.get(), //
rasterizer_future.get(), //
io_manager_future.get()) //
) {
return nullptr;
}
return shell;
}
3.6.5 创建Shell对象:Shell::Shell()

-> flutter/shell/common/shell.cc

创建Shell对象,成员变量taskrunners、settings以及vm赋初值

3.6.6 创建rasterizer对象

-> flutter/shell/common/rasterizer.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Rasterizer::Rasterizer(Delegate& delegate, TaskRunners task_runners)
: Rasterizer(delegate,
std::move(task_runners),
std::make_unique<flutter::CompositorContext>(
delegate.GetFrameBudget())) {}
Rasterizer::Rasterizer(
Delegate& delegate,
TaskRunners task_runners,
std::unique_ptr<flutter::CompositorContext> compositor_context)
: delegate_(delegate),
task_runners_(std::move(task_runners)),
compositor_context_(std::move(compositor_context)),
user_override_resource_cache_bytes_(false),
weak_factory_(this) {
FML_DCHECK(compositor_context_);
}

on_create_rasterizer方法等价于创建Rasterizer对象,在这个过程还会创建CompositorContext对象并赋值给compositorcontext

3.6.7 创建platform_view:on_create_platform_view

-> flutter/shell/platform/android/platform_view_android.cc

1
2
3
4
5
6
7
8
9
10
11
12
PlatformViewAndroid::PlatformViewAndroid(
PlatformView::Delegate& delegate,
flutter::TaskRunners task_runners,
fml::jni::JavaObjectWeakGlobalRef java_object,
bool use_software_rendering)
: PlatformView(delegate, std::move(task_runners)),
java_object_(java_object),
android_surface_(AndroidSurface::Create(use_software_rendering)) {
FML_CHECK(android_surface_)
<< "Could not create an OpenGL, Vulkan or Software surface to setup "
"rendering.";
}

on_create_platform_view方法的核心就是创建PlatformViewAndroid对象。

-> flutter/shell/platform/android/android_surface.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::unique_ptr<AndroidSurface> AndroidSurface::Create(
bool use_software_rendering) {
if (use_software_rendering) {
auto software_surface = std::make_unique<AndroidSurfaceSoftware>();
return software_surface->IsValid() ? std::move(software_surface) : nullptr;
}
#if SHELL_ENABLE_VULKAN
auto vulkan_surface = std::make_unique<AndroidSurfaceVulkan>();
return vulkan_surface->IsValid() ? std::move(vulkan_surface) : nullptr;
#else // SHELL_ENABLE_VULKAN
auto gl_surface = std::make_unique<AndroidSurfaceGL>();
return gl_surface->IsOffscreenContextValid() ? std::move(gl_surface)
: nullptr;
#endif // SHELL_ENABLE_VULKAN
}

有三种不同的AndroidSurface。

3.6.8 创建vsync waiter:platform_view->CreateVSyncWaiter

-> flutter/shell/platform/android/platform_view_android.cc

1
2
3
std::unique_ptr<VsyncWaiter> PlatformViewAndroid::CreateVSyncWaiter() {
return std::make_unique<VsyncWaiterAndroid>(task_runners_);
}

-> flutter/shell/platform/android/vsync_waiter_android.cc

1
2
VsyncWaiterAndroid::VsyncWaiterAndroid(flutter::TaskRunners task_runners)
: VsyncWaiter(std::move(task_runners)) {}

创建VsyncWaiterAndroid对象,也会初始化父类VsyncWaiter。

3.6.9 创建ShellIOManager

-> flutter/shell/common/shell_io_manager.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ShellIOManager::ShellIOManager(
sk_sp<GrContext> resource_context,
std::shared_ptr<fml::SyncSwitch> is_gpu_disabled_sync_switch,
fml::RefPtr<fml::TaskRunner> unref_queue_task_runner)
: resource_context_(std::move(resource_context)),
resource_context_weak_factory_(
resource_context_ ? std::make_unique<fml::WeakPtrFactory<GrContext>>(
resource_context_.get())
: nullptr),
unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>(
std::move(unref_queue_task_runner),
fml::TimeDelta::FromMilliseconds(8),
GetResourceContext())),
weak_factory_(this),
is_gpu_disabled_sync_switch_(is_gpu_disabled_sync_switch) {
if (!resource_context_) {
#ifndef OS_FUCHSIA
FML_DLOG(WARNING) << "The IO manager was initialized without a resource "
"context. Async texture uploads will be disabled. "
"Expect performance degradation.";
#endif // OS_FUCHSIA
}
}

ShellIOManager的初始化过程,会创建GrContext和SkiaUnrefQueue对象。

3.6.10 创建Animator

-> flutter/shell/common/animator.cc

3.6.11 创建Engine

-> flutter/shell/common/engine.cc

创建RuntimeController对象。

-> flutter/runtime/runtime_controller.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
RuntimeController::RuntimeController(
RuntimeDelegate& p_client,
DartVM* p_vm,
fml::RefPtr<const DartSnapshot> p_isolate_snapshot,
TaskRunners p_task_runners,
fml::WeakPtr<SnapshotDelegate> p_snapshot_delegate,
fml::WeakPtr<IOManager> p_io_manager,
fml::RefPtr<SkiaUnrefQueue> p_unref_queue,
fml::WeakPtr<ImageDecoder> p_image_decoder,
std::string p_advisory_script_uri,
std::string p_advisory_script_entrypoint,
const std::function<void(int64_t)>& idle_notification_callback,
const WindowData& p_window_data,
const fml::closure& p_isolate_create_callback,
const fml::closure& p_isolate_shutdown_callback,
std::shared_ptr<const fml::Mapping> p_persistent_isolate_data)
: client_(p_client),
vm_(p_vm),
isolate_snapshot_(std::move(p_isolate_snapshot)),
task_runners_(p_task_runners),
snapshot_delegate_(p_snapshot_delegate),
io_manager_(p_io_manager),
unref_queue_(p_unref_queue),
image_decoder_(p_image_decoder),
advisory_script_uri_(p_advisory_script_uri),
advisory_script_entrypoint_(p_advisory_script_entrypoint),
idle_notification_callback_(idle_notification_callback),
window_data_(std::move(p_window_data)),
isolate_create_callback_(p_isolate_create_callback),
isolate_shutdown_callback_(p_isolate_shutdown_callback),
persistent_isolate_data_(std::move(p_persistent_isolate_data)) {
// Create the root isolate as soon as the runtime controller is initialized.
// It will be run at a later point when the engine provides a run
// configuration and then runs the isolate.
auto strong_root_isolate =
// 创建RootIsolate[见3.6.11.2]
DartIsolate::CreateRootIsolate(vm_->GetVMData()->GetSettings(), //
isolate_snapshot_, //
task_runners_, //
// 创建Window对象[3.6.11.1]
std::make_unique<Window>(this), //
snapshot_delegate_, //
io_manager_, //
unref_queue_, //
image_decoder_, //
p_advisory_script_uri, //
p_advisory_script_entrypoint, //
nullptr, //
isolate_create_callback_, //
isolate_shutdown_callback_ //
)
.lock();
FML_CHECK(strong_root_isolate) << "Could not create root isolate.";
// The root isolate ivar is weak.
root_isolate_ = strong_root_isolate;
strong_root_isolate->SetReturnCodeCallback([this](uint32_t code) {
root_isolate_return_code_ = {true, code};
});
if (auto* window = GetWindowIfAvailable()) {
tonic::DartState::Scope scope(strong_root_isolate);
window->DidCreateIsolate();
if (!FlushRuntimeStateToIsolate()) {
FML_DLOG(ERROR) << "Could not setup initial isolate state.";
}
} else {
FML_DCHECK(false) << "RuntimeController created without window binding.";
}
FML_DCHECK(Dart_CurrentIsolate() == nullptr);
}
3.6.11.1 创建Window:-> flutter/lib/ui/window/window.cc
3.6.11.2 创建RootIsolate:DartIsolate::CreateRootIsolate

-> flutter/runtime/dart_isolate.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
std::weak_ptr<DartIsolate> DartIsolate::CreateRootIsolate(
const Settings& settings,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
TaskRunners task_runners,
std::unique_ptr<Window> window,
fml::WeakPtr<SnapshotDelegate> snapshot_delegate,
fml::WeakPtr<IOManager> io_manager,
fml::RefPtr<SkiaUnrefQueue> unref_queue,
fml::WeakPtr<ImageDecoder> image_decoder,
std::string advisory_script_uri,
std::string advisory_script_entrypoint,
Dart_IsolateFlags* flags,
const fml::closure& isolate_create_callback,
const fml::closure& isolate_shutdown_callback) {
TRACE_EVENT0("flutter", "DartIsolate::CreateRootIsolate");
// The child isolate preparer is null but will be set when the isolate is
// being prepared to run.
auto isolate_group_data =
std::make_unique<std::shared_ptr<DartIsolateGroupData>>(
std::shared_ptr<DartIsolateGroupData>(new DartIsolateGroupData(
settings, // settings
std::move(isolate_snapshot), // isolate snapshot
advisory_script_uri, // advisory URI
advisory_script_entrypoint, // advisory entrypoint
nullptr, // child isolate preparer
isolate_create_callback, // isolate create callback
isolate_shutdown_callback // isolate shutdown callback
)));
// 创建DartIsolate
auto isolate_data = std::make_unique<std::shared_ptr<DartIsolate>>(
std::shared_ptr<DartIsolate>(new DartIsolate(
settings, // settings
task_runners, // task runners
std::move(snapshot_delegate), // snapshot delegate
std::move(io_manager), // IO manager
std::move(unref_queue), // Skia unref queue
std::move(image_decoder), // Image Decoder
advisory_script_uri, // advisory URI
advisory_script_entrypoint, // advisory entrypoint
true // is_root_isolate
)));
DartErrorString error;
Dart_Isolate vm_isolate =
CreateDartIsolateGroup(std::move(isolate_group_data),
std::move(isolate_data), flags, error.error());
if (error) {
FML_LOG(ERROR) << "CreateDartIsolateGroup failed: " << error.str();
}
if (vm_isolate == nullptr) {
return {};
}
std::shared_ptr<DartIsolate>* root_isolate_data =
static_cast<std::shared_ptr<DartIsolate>*>(Dart_IsolateData(vm_isolate));
// 只有root_isolate_data能和window交互
(*root_isolate_data)->SetWindow(std::move(window));
return (*root_isolate_data)->GetWeakIsolatePtr();
}
3.6.12 shell->Setup

-> flutter/shell/common/shell.cc

参考

深入理解Flutter引擎启动