8. Flutte3.0 遙遙領(lǐng)先系列|一文教你完全掌握啟動(dòng)機(jī)制

目錄
1.Flutter的3層架構(gòu)
2.android開始啟動(dòng)flutter源碼分析
3.核心類分析
). FlutterActivityAndFragmentDelegate
). FlutterEngine
).FlutterView
). FlutterEngine
).DartExecutor
4.4個(gè)線程比較
5.flutter入庫的啟動(dòng)邏輯

1.Flutter架構(gòu)的核心架構(gòu)

3層結(jié)構(gòu).jpg

Flutter的架構(gòu)原理

Flutter架構(gòu)采用分層設(shè)計(jì),從下到上分為三層,依次為:Embedder、Engine、Framework。即嵌入層,引擎層, 框架層

1).Embedder是操作系統(tǒng)適配層,實(shí)現(xiàn)了渲染Surface設(shè)置,線程設(shè)置,以及平臺(tái)插件等平臺(tái)相關(guān)特性的適配。(操作系統(tǒng)適配層 )
從這里我們可以看到,F(xiàn)lutter平臺(tái)相關(guān)特性并不多,這就使得從框架層面保持跨端一致性的成本相對(duì)較低。
2). Engine層主要包含Skia、Dart和Text,實(shí)現(xiàn)了Flutter的渲染引擎、文字排版、事件處理和Dart運(yùn)行時(shí)等功能。(渲染,事件)
Skia和Text為上層接口提供了調(diào)用底層渲染和排版的能力,Dart則為Flutter提供了運(yùn)行時(shí)調(diào)用Dart和渲染引擎的能力。而Engine層的作用,則是將它們組合起來,從它們生成的數(shù)據(jù)中實(shí)現(xiàn)視圖渲染。
3). Framework層則是一個(gè)用Dart實(shí)現(xiàn)的UI SDK,包含了動(dòng)畫、圖形繪制和手勢(shì)識(shí)別等功能。(sdk)
為了在繪制控件等固定樣式的圖形時(shí)提供更直觀、更方便的接口,F(xiàn)lutter還基于這些基礎(chǔ)能力,根據(jù)Material和Cupertino兩種視覺設(shè)計(jì)風(fēng)格封裝了一套UI組件庫。我們?cè)陂_發(fā)Flutter的時(shí)候,可以直接使用這些組件庫。

2.啟動(dòng)源碼分析

如果我們想要查看 Flutter 引擎底層源碼,就需要用到 Ninja 編譯, Ninja 的安裝步驟可以點(diǎn)擊查看

需要從3大結(jié)構(gòu)講解出源碼分析的內(nèi)容!

  • FlutterApplication.java的onCreate過程:初始化配置文件/加載libflutter.so/注冊(cè)JNI方法;

如果是純flutter項(xiàng)目, 入口就是這個(gè), 最終調(diào)用到main.dart里面的runAPP

架構(gòu)圖如下:
11111.jpg
調(diào)用順序.jpg
class MainActivity: FlutterActivity() {
    
}

onCreate: 創(chuàng)建FlutterView、Dart虛擬機(jī)、Engine、Isolate、taskRunner等對(duì)象,最終執(zhí)行執(zhí)行到Dart的main()方法,處理整個(gè)Dart業(yè)務(wù)代碼。

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    switchLaunchThemeForNormalTheme();

    super.onCreate(savedInstanceState);

    delegate = new FlutterActivityAndFragmentDelegate(this);
    delegate.onAttach(this);
    delegate.onRestoreInstanceState(savedInstanceState);

    lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);

    configureWindowForTransparency();

    setContentView(createFlutterView());

    configureStatusBarForFullscreenFlutterExperience();
  }

FlutterActivityAndFragmentDelegate
代理類: 基本上view和引擎都是它創(chuàng)建的!
onAttach: 各種初始化操作

 void onAttach(@NonNull Context context) {
    ensureAlive();

    // When "retain instance" is true, the FlutterEngine will survive configuration
    // changes. Therefore, we create a new one only if one does not already exist.
    if (flutterEngine == null) {
      setupFlutterEngine();
    }

    if (host.shouldAttachEngineToActivity()) {
      // Notify any plugins that are currently attached to our FlutterEngine that they
      // are now attached to an Activity.
      //
      // Passing this Fragment's Lifecycle should be sufficient because as long as this Fragment
      // is attached to its Activity, the lifecycles should be in sync. Once this Fragment is
      // detached from its Activity, that Activity will be detached from the FlutterEngine, too,
      // which means there shouldn't be any possibility for the Fragment Lifecycle to get out of
      // sync with the Activity. We use the Fragment's Lifecycle because it is possible that the
      // attached Activity is not a LifecycleOwner.
      Log.v(TAG, "Attaching FlutterEngine to the Activity that owns this delegate.");
      flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle());
    }

    // Regardless of whether or not a FlutterEngine already existed, the PlatformPlugin
    // is bound to a specific Activity. Therefore, it needs to be created and configured
    // every time this Fragment attaches to a new Activity.
    // TODO(mattcarroll): the PlatformPlugin needs to be reimagined because it implicitly takes
    //                    control of the entire window. This is unacceptable for non-fullscreen
    //                    use-cases.
    platformPlugin = host.providePlatformPlugin(host.getActivity(), flutterEngine);

    host.configureFlutterEngine(flutterEngine);
    isAttached = true;
  }
3.1 FlutterActivityAndFragmentDelegate---創(chuàng)建的FlutterEngine
  public FlutterEngine(
      @NonNull Context context,
      @Nullable FlutterLoader flutterLoader,
      @NonNull FlutterJNI flutterJNI,
      @NonNull PlatformViewsController platformViewsController,
      @Nullable String[] dartVmArgs,
      boolean automaticallyRegisterPlugins,
      boolean waitForRestorationData,
      @Nullable FlutterEngineGroup group) {
    AssetManager assetManager;
    try {
      assetManager = context.createPackageContext(context.getPackageName(), 0).getAssets();
    } catch (NameNotFoundException e) {
      assetManager = context.getAssets();
    }

    FlutterInjector injector = FlutterInjector.instance();

    if (flutterJNI == null) {
      flutterJNI = injector.getFlutterJNIFactory().provideFlutterJNI();
    }
    this.flutterJNI = flutterJNI;

    this.dartExecutor = new DartExecutor(flutterJNI, assetManager);
    this.dartExecutor.onAttachedToJNI();

    DeferredComponentManager deferredComponentManager =
        FlutterInjector.instance().deferredComponentManager();

    accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI);
    deferredComponentChannel = new DeferredComponentChannel(dartExecutor);
    lifecycleChannel = new LifecycleChannel(dartExecutor);
    localizationChannel = new LocalizationChannel(dartExecutor);
    mouseCursorChannel = new MouseCursorChannel(dartExecutor);
    navigationChannel = new NavigationChannel(dartExecutor);
    platformChannel = new PlatformChannel(dartExecutor);
    restorationChannel = new RestorationChannel(dartExecutor, waitForRestorationData);
    settingsChannel = new SettingsChannel(dartExecutor);
    spellCheckChannel = new SpellCheckChannel(dartExecutor);
    systemChannel = new SystemChannel(dartExecutor);
    textInputChannel = new TextInputChannel(dartExecutor);
  @VisibleForTesting
  /* package */ void setupFlutterEngine() {
    Log.v(TAG, "Setting up FlutterEngine.");

    // First, check if the host wants to use a cached FlutterEngine.
    String cachedEngineId = host.getCachedEngineId();
    if (cachedEngineId != null) {
      flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
      isFlutterEngineFromHost = true;
      if (flutterEngine == null) {
        throw new IllegalStateException(
            "The requested cached FlutterEngine did not exist in the FlutterEngineCache: '"
                + cachedEngineId
                + "'");
      }
      return;
    }

    // Second, defer to subclasses for a custom FlutterEngine.
    flutterEngine = host.provideFlutterEngine(host.getContext());
    if (flutterEngine != null) {
      isFlutterEngineFromHost = true;
      return;
    }

    // Third, check if the host wants to use a cached FlutterEngineGroup
    // and create new FlutterEngine using FlutterEngineGroup#createAndRunEngine
    String cachedEngineGroupId = host.getCachedEngineGroupId();
    if (cachedEngineGroupId != null) {
      FlutterEngineGroup flutterEngineGroup =
          FlutterEngineGroupCache.getInstance().get(cachedEngineGroupId);
      if (flutterEngineGroup == null) {
        throw new IllegalStateException(
            "The requested cached FlutterEngineGroup did not exist in the FlutterEngineGroupCache: '"
                + cachedEngineGroupId
                + "'");
      }

      flutterEngine =
          flutterEngineGroup.createAndRunEngine(
              addEntrypointOptions(new FlutterEngineGroup.Options(host.getContext())));
      isFlutterEngineFromHost = false;
      return;
    }

    // Our host did not provide a custom FlutterEngine. Create a FlutterEngine to back our
    // FlutterView.
    Log.v(
        TAG,
        "No preferred FlutterEngine was provided. Creating a new FlutterEngine for"
            + " this FlutterFragment.");

    FlutterEngineGroup group =
        engineGroup == null
            ? new FlutterEngineGroup(host.getContext(), host.getFlutterShellArgs().toArray())
            : engineGroup;
    flutterEngine =
        group.createAndRunEngine(
            addEntrypointOptions(
                new FlutterEngineGroup.Options(host.getContext())
                    .setAutomaticallyRegisterPlugins(false)
                    .setWaitForRestorationData(host.shouldRestoreAndSaveState())));
    isFlutterEngineFromHost = false;
  }
3.2 FlutterEngine: 引擎。(重要)
    1). FlutterEngine 是一個(gè)獨(dú)立的 Flutter 運(yùn)行環(huán)境容器,通過它可以在 Android 應(yīng)用程序中運(yùn)行 Dart 代碼。

使用 FlutterEngine 執(zhí)行 Dart 或 Flutter 代碼需要先通過 FlutterEngine 獲取 DartExecutor 引用,然后調(diào)用 DartExecutor 的executeDartEntrypoint(DartExecutor.DartEntrypoint)執(zhí)行 Dart 代碼即可
2). FlutterEngine 中的 Dart 代碼可以在后臺(tái)執(zhí)行,也可以使用附帶的 FlutterRenderer 和 Dart 代碼將 Dart 端 UI 效果渲染到屏幕上,渲染可以開始和停止,從而允許 FlutterEngine 從 UI 交互轉(zhuǎn)移到僅進(jìn)行數(shù)據(jù)處理,然后又返回到 UI 交互的能力v
3). 在Flutter引擎啟動(dòng)也初始化完成后,執(zhí)行FlutterActivityDelegate.runBundle()加載Dart代碼,其中entrypoint和libraryPath分別代表主函數(shù)入口的函數(shù)名”main”和所對(duì)應(yīng)庫的路徑, 經(jīng)過層層調(diào)用后開始執(zhí)行dart層的main()方法,執(zhí)行runApp()的過程,這便開啟執(zhí)行整個(gè)Dart業(yè)務(wù)代碼。

四大關(guān)系: FlutterEngine,DartExecutor,Dart VM, Isloate

FlutterJNI:engine 層的 JNI 接口都在這里面注冊(cè)、綁定。通過他可以調(diào)用 engine 層的 c/c++ 代碼
DartExecutor:用于執(zhí)行 Dart 代碼(調(diào)用 DartExecutor 的executeDartEntrypoint(DartExecutor.DartEntrypoint)即可執(zhí)行,一個(gè) FlutterEngine 執(zhí)行一次)
FlutterRenderer:FlutterRenderer 實(shí)例 attach 上一個(gè) RenderSurface 也就是之前說的 FlutterView
這里 FlutterEngine 與 DartExecutor、Dart VM、Isolate 的關(guān)系大致可以歸納如下:
一個(gè)Native進(jìn)程只有一個(gè)DartVM。
一個(gè)DartVM(或說一個(gè)Native進(jìn)程)可以有多個(gè)FlutterEngine。
多個(gè)FlutterEngine運(yùn)行在各自的Isolate中,他們的內(nèi)存數(shù)據(jù)不共享,需要通過Isolate事先設(shè)置的port(頂級(jí)函數(shù))通訊。
FlutterEngine可以后臺(tái)運(yùn)行代碼,不渲染UI;也可以通過FlutterRender渲染UI。

多引擎.jpg

圖解:在platform_view_android_jni.cc的AttachJNI過程會(huì)初始化AndroidShellHolder對(duì)象,該對(duì)象初始化過程的主要工作

  1. 創(chuàng)建AndroidShellHolder對(duì)象,會(huì)初始化ThreadHost,并創(chuàng)建1.ui, 1.gpu, 1.io這3個(gè)線程。每個(gè)線程Thread初始化過程,都會(huì)創(chuàng)建相應(yīng)的MessageLoop、TaskRunner對(duì)象,然后進(jìn)入pollOnce輪詢等待狀態(tài);
  2. 創(chuàng)建Shell對(duì)象,設(shè)置默認(rèn)log只輸出ERROR級(jí)別,除非在啟動(dòng)的時(shí)候帶上參數(shù)verbose_logging,則會(huì)打印出INFO級(jí)別的日志;
  3. 當(dāng)進(jìn)程存在正在運(yùn)行DartVM,則獲取其強(qiáng)引用,復(fù)用該DartVM,否則新創(chuàng)建一個(gè)Dart虛擬機(jī);
  4. 在Shell::CreateShellOnPlatformThread()過程執(zhí)行如下操作:
    • 主線程中創(chuàng)建PlatformViewAndroid對(duì)象,AndroidSurfaceGL、GPUSurfaceGL以及VsyncWaiterAndroid對(duì)象;
    • io線程中創(chuàng)建ShellIOManager對(duì)象,GrContext、SkiaUnrefQueue對(duì)象
    • gpu線程中創(chuàng)建Rasterizer對(duì)象,CompositorContext對(duì)象
    • ui線程中創(chuàng)建Engine、Animator對(duì)象,RuntimeController、Window對(duì)象,以及DartIsolate、Isolate對(duì)象

可見,每一個(gè)FlutterActivity都有相對(duì)應(yīng)的FlutterView、AndroidShellHolder、Shell、Engine、Animator、PlatformViewAndroid、RuntimeController、Window等對(duì)象。但每一個(gè)進(jìn)進(jìn)程DartVM獨(dú)有一份;

不錯(cuò)的圖.jpg
3.3 FlutterActivityAndFragmentDelegate---創(chuàng)建的view

createFlutterView
FlutterView:

  View onCreateView(
      LayoutInflater inflater,
      @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState,
      int flutterViewId,
      boolean shouldDelayFirstAndroidViewDraw) {
    Log.v(TAG, "Creating FlutterView.");
    ensureAlive();

    if (host.getRenderMode() == RenderMode.surface) {
      FlutterSurfaceView flutterSurfaceView =
          new FlutterSurfaceView(
              host.getContext(), host.getTransparencyMode() == TransparencyMode.transparent);

      // Allow our host to customize FlutterSurfaceView, if desired.
      host.onFlutterSurfaceViewCreated(flutterSurfaceView);

      // Create the FlutterView that owns the FlutterSurfaceView.
      flutterView = new FlutterView(host.getContext(), flutterSurfaceView);
    } else {
      FlutterTextureView flutterTextureView = new FlutterTextureView(host.getContext());

      flutterTextureView.setOpaque(host.getTransparencyMode() == TransparencyMode.opaque);

      // Allow our host to customize FlutterSurfaceView, if desired.
      host.onFlutterTextureViewCreated(flutterTextureView);

      // Create the FlutterView that owns the FlutterTextureView.
      flutterView = new FlutterView(host.getContext(), flutterTextureView);
    }

    // Add listener to be notified when Flutter renders its first frame.
    flutterView.addOnFirstFrameRenderedListener(flutterUiDisplayListener);

    Log.v(TAG, "Attaching FlutterEngine to FlutterView.");
    flutterView.attachToFlutterEngine(flutterEngine); // flutter綁定 flutterEngine
    flutterView.setId(flutterViewId);

    SplashScreen splashScreen = host.provideSplashScreen();
    return flutterView;
  }

attachToFlutterEngine:這個(gè)方法里將FlutterSurfaceView的Surface提供給指定的FlutterRender,用于將Flutter UI繪制到當(dāng)前的FlutterSurfaceView

FlutterNativeView

 void onStart() {
    Log.v(TAG, "onStart()");
    ensureAlive();
    doInitialFlutterViewRun();
    // This is a workaround for a bug on some OnePlus phones. The visibility of the application
    // window is still true after locking the screen on some OnePlus phones, and shows a black
    // screen when unlocked. We can work around this by changing the visibility of FlutterView in
    // onStart and onStop.
    // See https://github.com/flutter/flutter/issues/93276
    if (previousVisibility != null) {
      flutterView.setVisibility(previousVisibility);
    }
  }
 private void doInitialFlutterViewRun() {
    // Don't attempt to start a FlutterEngine if we're using a cached FlutterEngine.
    if (host.getCachedEngineId() != null) {
      return;
    }

    if (flutterEngine.getDartExecutor().isExecutingDart()) {
      // No warning is logged because this situation will happen on every config
      // change if the developer does not choose to retain the Fragment instance.
      // So this is expected behavior in many cases.
      return;
    }
    String initialRoute = host.getInitialRoute();
    if (initialRoute == null) {
      initialRoute = maybeGetInitialRouteFromIntent(host.getActivity().getIntent());
      if (initialRoute == null) {
        initialRoute = DEFAULT_INITIAL_ROUTE;
      }
    }
    @Nullable String libraryUri = host.getDartEntrypointLibraryUri();
    Log.v(
        TAG,
        "Executing Dart entrypoint: "
                    + host.getDartEntrypointFunctionName()
                    + ", library uri: "
                    + libraryUri
                == null
            ? "\"\""
            : libraryUri + ", and sending initial route: " + initialRoute);

    // The engine needs to receive the Flutter app's initial route before executing any
    // Dart code to ensure that the initial route arrives in time to be applied.
    flutterEngine.getNavigationChannel().setInitialRoute(initialRoute);

    String appBundlePathOverride = host.getAppBundlePath();
    if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
      appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath();
    }

    // Configure the Dart entrypoint and execute it.
    DartExecutor.DartEntrypoint entrypoint =
        libraryUri == null
            ? new DartExecutor.DartEntrypoint(
                appBundlePathOverride, host.getDartEntrypointFunctionName())
            : new DartExecutor.DartEntrypoint(
                appBundlePathOverride, libraryUri, host.getDartEntrypointFunctionName());
    flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs());
  }

DartExecutor

 public void executeDartEntrypoint(
      @NonNull DartEntrypoint dartEntrypoint, @Nullable List<String> dartEntrypointArgs) {
    if (isApplicationRunning) {
      Log.w(TAG, "Attempted to run a DartExecutor that is already running.");
      return;
    }

    TraceSection.begin("DartExecutor#executeDartEntrypoint");
    try {
      Log.v(TAG, "Executing Dart entrypoint: " + dartEntrypoint);
      flutterJNI.runBundleAndSnapshotFromLibrary(
          dartEntrypoint.pathToBundle,
          dartEntrypoint.dartEntrypointFunctionName,
          dartEntrypoint.dartEntrypointLibrary,
          assetManager,
          dartEntrypointArgs);

      isApplicationRunning = true;
    } finally {
      TraceSection.end();
    }
  }

FlutterJNI

 @UiThread
  public void runBundleAndSnapshotFromLibrary(
      @NonNull String bundlePath,
      @Nullable String entrypointFunctionName,
      @Nullable String pathToEntrypointFunction,
      @NonNull AssetManager assetManager,
      @Nullable List<String> entrypointArgs) {
    ensureRunningOnMainThread();
    ensureAttachedToNative();
    nativeRunBundleAndSnapshotFromLibrary(
        nativeShellHolderId,
        bundlePath,
        entrypointFunctionName,
        pathToEntrypointFunction,
        assetManager,
        entrypointArgs);
  }
  private native void nativeRunBundleAndSnapshotFromLibrary(
      long nativeShellHolderId,
      @NonNull String bundlePath,
      @Nullable String entrypointFunctionName,
      @Nullable String pathToEntrypointFunction,
      @NonNull AssetManager manager,
      @Nullable List<String> entrypointArgs);

AndroidShellHolder: C++

void AndroidShellHolder::Launch(std::shared_ptr<AssetManager> asset_manager,
                                const std::string& entrypoint,
                                const std::string& libraryUrl) {
  ...
  shell_->RunEngine(std::move(config.value()));
}

Shell. : C++

Shell 的作用?

a、Shell 是 Flutter 的底層框架,它提供了一個(gè)跨平臺(tái)的渲染引擎、視圖系統(tǒng)和一套基礎(chǔ)庫。Shell 是構(gòu)建 Flutter 應(yīng)用程序的基礎(chǔ),它將應(yīng)用程序邏輯和 Flutter 引擎的交互封裝在一起。
b、Flutter 應(yīng)用程序通常包含一個(gè)或多個(gè) Shell,每個(gè) Shell 包含一個(gè)渲染線程和一個(gè) Dart 執(zhí)行上下文。Shell 接收來自 Dart 代碼的指令,并將其翻譯成圖形、動(dòng)畫和其他視覺效果,以及響應(yīng)用戶的輸入事件。Shell 還提供了對(duì) Flutter 引擎的訪問,使開發(fā)者可以配置引擎和訪問它的功能。
[-> flutter/shell/common/shell.cc]

void Shell::RunEngine(
    RunConfiguration run_configuration,
    const std::function<void(Engine::RunStatus)>& result_callback) {
    ...
  fml::TaskRunner::RunNowOrPostTask(
      task_runners_.GetUITaskRunner(), // [10]
      fml::MakeCopyable(
          [run_configuration = std::move(run_configuration),
           weak_engine = weak_engine_, result]() mutable {
            ...
            auto run_result = weak_engine->Run(std::move(run_configuration));
            ...
            result(run_result);
          }));
}

Engine. : C++

// ./shell/common/engine.cc
Engine::RunStatus Engine::Run(RunConfiguration configuration) {
  ...
  last_entry_point_ = configuration.GetEntrypoint();
  last_entry_point_library_ = configuration.GetEntrypointLibrary();
  auto isolate_launch_status =
      PrepareAndLaunchIsolate(std::move(configuration)); // [11]
  ...
  std::shared_ptr<DartIsolate> isolate =
      runtime_controller_->GetRootIsolate().lock();

  bool isolate_running =
      isolate && isolate->GetPhase() == DartIsolate::Phase::Running;

  if (isolate_running) {
    ...
    std::string service_id = isolate->GetServiceId();
    fml::RefPtr<PlatformMessage> service_id_message =
        fml::MakeRefCounted<flutter::PlatformMessage>(
            kIsolateChannel, // 此處設(shè)置為IsolateChannel
            std::vector<uint8_t>(service_id.begin(), service_id.end()),
            nullptr);
    HandlePlatformMessage(service_id_message); // [12]
  }
  return isolate_running ? Engine::RunStatus::Success
                         : Engine::RunStatus::Failure;
}

DartIsolate

[[nodiscard]] bool DartIsolate::Run(const std::string& entrypoint_name,
                                    const std::vector<std::string>& args,
                                    const fml::closure& on_run) {
  if (phase_ != Phase::Ready) {
    return false;
  }

  tonic::DartState::Scope scope(this);

  auto user_entrypoint_function =
      Dart_GetField(Dart_RootLibrary(), 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;
}

這里首先將 Isolate 的狀態(tài)設(shè)置為 Running 接著調(diào)用 dart 的 main 方法。這里 InvokeMainEntrypoint 是執(zhí)行 main 方法的關(guān)鍵

[[nodiscard]] 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}))) {
    return false;
  }
  return true;
}
問題: Dart中編寫的Widget最終是如何繪制到平臺(tái)View上的呢???

PlatformView:
為了能讓一些現(xiàn)有的 native 控件直接引用到 Flutter app 中,F(xiàn)lutter 團(tuán)隊(duì)提供了 AndroidView 、UIKitView 兩個(gè) widget 來滿足需求
platform view 就是 AndroidView 和 UIKitView 的總稱

問題:FlutterActivity 這些 Java 類是屬于哪一層呢?是 framework 還是 engine 亦或是 platform 呢

4.4個(gè)線程比較

1). Platform Task Runner (或者叫 Platform Thread)的功能是要處理平臺(tái)(android/iOS)的消息。舉個(gè)簡(jiǎn)單的例子,我們 MethodChannel 的回調(diào)方法 onMethodCall 就是在這個(gè)線程上
2). UI Task Runner用于執(zhí)行Root Isolate代碼,它運(yùn)行在線程對(duì)應(yīng)平臺(tái)的線程上,屬于子線程。同時(shí),Root isolate在引擎啟動(dòng)時(shí)會(huì)綁定了不少Flutter需要的函數(shù)方法,以便進(jìn)行渲染操作。
3). GPU Task Runner主要用于執(zhí)行設(shè)備GPU的指令。在UI Task Runner 創(chuàng)建layer tree,在GPU Task Runner將Layer Tree提供的信息轉(zhuǎn)化為平臺(tái)可執(zhí)行的GPU指令。除了將Layer Tree提供的信息轉(zhuǎn)化為平臺(tái)可執(zhí)行的GPU指令,GPU Task Runner同時(shí)也負(fù)責(zé)管理每一幀繪制所需要的GPU資源,包括平臺(tái)Framebuffer的創(chuàng)建,Surface生命周期管理,以及Texture和Buffers的繪制時(shí)機(jī)等
4). IO Task Runner也運(yùn)行在平臺(tái)對(duì)應(yīng)的子線程中,主要作用是做一些預(yù)先處理的讀取操作,為GPU Runner的渲染操作做準(zhǔn)備。我們可以認(rèn)為IO Task Runner是GPU Task Runner的助手,它可以減少GPU Task Runner的額外工作。例如,在Texture的準(zhǔn)備過程中,IO Runner首先會(huì)讀取壓縮的圖片二進(jìn)制數(shù)據(jù),并將其解壓轉(zhuǎn)換成GPU能夠處理的格式,然后再將數(shù)據(jù)傳遞給GPU進(jìn)行渲染。

4大線程總結(jié).jpg

5.flutter入庫的啟動(dòng)邏輯

三行代碼代表了Flutter APP 啟動(dòng)的三個(gè)主流程:

binding初始化(ensureInitialized)
創(chuàng)建根 widget,綁定根節(jié)點(diǎn)(scheduleAttachRootWidget)
繪制熱身幀(scheduleWarmUpFrame)

void runApp(Widget app) { 
    WidgetsFlutterBinding.ensureInitialized()
      ..scheduleAttachRootWidget(app)
      ..scheduleWarmUpFrame();
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容