Flutter OHOS Flutter Engine 异步创建与销毁说明文档

Flutter 新增异步创建和销毁 Engine 的能力

ts 复制代码
// 异步创建 engine, 相关文件 FlutterEngineGroup.ets
createAndRunEngineByOptionsAsync(options: Options): Promise<FlutterEngine> {
    // ...
}
// 异步销毁 engine, 相关文件 FlutterEngine.ets
destroyAsync(): Promise<void> {
    // ...
}

使用场景

需要创建多个Flutter Engine,并避免engine的创建、销毁流程卡住主线程的场景。

使用示例

ohos/entry/src/main/ets/entryability/EntryAbility.ets

ts 复制代码
export default class EntryAbility extends UIAbility implements ExclusiveAppComponent<UIAbility> {

  detachFromFlutterEngine(): void {
    // throw new Error('Method not implemented.');
  }

  getAppComponent(): UIAbility {
    return this;
  }

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    FlutterManager.getInstance().pushUIAbility(this);
  }

  onDestroy(): void | Promise<void> {
    FlutterManager.getInstance().popUIAbility(this);
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.getMainWindowSync().setWindowLayoutFullScreen(true);
    FlutterManager.getInstance().pushWindowStage(this, windowStage);
    // 页面路径需要在配置文件 main_pages.json 中声明,缺失会导致白屏。
    // 配置文件路径: ohos/entry/src/main/resources/base/profile/main_pages.json
    // windowStage.loadContent('pages/Index');
    windowStage.loadContent('pages/FlutterAsyncPage');
  }

  onWindowStageDestroy() {
    FlutterManager.getInstance().popWindowStage(this);
  }
}

ohos/entry/src/main/ets/pages/FlutterAsyncPage.ets

ts 复制代码
// `FlutterEngineGroup` 用于管理多个 Flutter 引擎,并支持异步创建。
const engines = new FlutterEngineGroup();

@Entry()
@Preview
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext
  private flutterView: FlutterView | null = null;
  private engine?: FlutterEngine;
  private isAlive: boolean = false;

  build() {
    Stack() {
      FlutterPage({
        viewId: this.flutterView?.getId(),
        // ...
      })
    }
  }

  aboutToAppear(): void {
    this.isAlive = true;
    this.flutterView = FlutterManager.getInstance().createFlutterView(this.context);
    this.init()
  }

  async init() {
    let uiAbility: EntryAbility = FlutterManager.getInstance().getUIAbility(this.context) as EntryAbility;
    // 确保 Flutter Engine 所需的加载器已就绪
    engines.checkLoader(this.context, []);
    // DartEntrypoint.createDefault() 在 Flutter Engine 所需环境准备就绪后才可调用,否则会抛出异常。
    let options: Options = new Options(this.context).setDartEntrypoint(DartEntrypoint.createDefault());
    // 异步创建 Flutter Engine 对象
    engines.createAndRunEngineByOptionsAsync(options).then((engine) => {
      if (!this.isAlive) {
        engine?.destroySync();
        return;
      }
      this.engine = engine;
      // engine 相关生命周期处理
      engine?.getLifecycleChannel()?.appIsResumed()
      engine?.getAbilityControlSurface()?.attachToAbility(uiAbility);
      // flutterView 相关生命周期处理
      this.flutterView?.onWindowCreated();
      this.flutterView?.attachToFlutterEngine(engine);
      // 注册插件
      GeneratedPluginRegistrant.registerWith(engine);
      [new CustomPlugin(), new BatteryPlugin(), new PicturePlugin()]
        .forEach(item => {
          engine.getPlugins()?.add(item);
        })
      // 注册 PlatformViewFactory
      // engine.getPlatformViewsController()?.getRegistry().registerViewFactory(viewTypeId, factory)
    })
  }

  aboutToDisappear(): void {
    this.isAlive = false;
    // flutterView 相关生命周期处理
    this.flutterView?.detachFromFlutterEngine()
    this.flutterView?.onDestroy()
    // engine 相关生命周期处理
    this.engine?.getLifecycleChannel()?.appIsDetached()
    this.engine?.getAbilityControlSurface()?.detachFromAbility();
    this.engine?.destroyAsync()
    this.engine = undefined;
    this.flutterView = undefined;
  }

  onPageShow(): void {
    this.engine?.getLifecycleChannel()?.appIsResumed()
  }
  
  onPageHide(): void {
    this.engine?.getLifecycleChannel()?.appIsPaused()
  }

  // ...
}

相关验证场景

  1. flutter create async_engine_demo 创建的计数器界面
  2. PlatformView 相关场景
    1. 原生组件
    2. 图片显示
    3. 视频播放
    4. WebView

参考demo

相关推荐
贾伟康4 小时前
HarmonyOS API 26 Navigation 跨包路由:router_map、HSP 按需加载与失败回落
harmonyos·arkts·模块化·navigation·hsp
KevinChaos4 小时前
阳台小花园开发手记 04|HarmonyOS 7.0 互动卡片:倾斜手机时的卡片效果
华为·harmonyos
威哥爱编程9 小时前
模拟面试智能体开发实战 04:面试聊到哪算哪?用状态机把整场面试编排起来
python·agent·harmonyos
威哥爱编程9 小时前
模拟面试智能体开发实战 03:AI 面试官太客气?人设 Prompt 让它像个真考官
python·agent·harmonyos
贾伟康13 小时前
HarmonyOS API 26 Navigation 导航栏位置:navBarPosition、左右布局与折叠屏适配
harmonyos·arkts·arkui·navigation·折叠屏
贾伟康1 天前
HarmonyOS API 26 DevEco Code 需求到 ArkTS 骨架的提示词分层
harmonyos·arkts·ai coding·deveco code·工程提效
威哥爱编程1 天前
模拟面试智能体开发实战 02:回答等半分钟,谁还愿意练?把服务端和流式输出搭起来
python·agent·harmonyos
威哥爱编程1 天前
模拟面试智能体开发实战 01:面试挂了都不知道挂在哪?用 Python 给自己造一个随叫随到的 AI 面试官
python·agent·harmonyos
贾伟康1 天前
HarmonyOS API 26 HMAF Skill 可解释任务计划与失败回退
harmonyos·arkts·智能体·skill·hmaf
贾伟康1 天前
HarmonyOS API 26 HMAF 2.0 意图解析的可解释动作图
harmonyos·arkts·智能体·a2a·hmaf