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

相关推荐
默 语9 小时前
HarmonyOS7 拖拽事件实战:从 onPreDrag 八阶段到 onDrop 投放(附完整案例)
harmonyos
杜子不疼.10 小时前
从 Apache HTTP Server 到 CivetWeb:在鸿蒙 PC 的 3.1 MiB HAP 里嵌入 Web 服务器
前端·apache·harmonyos
默 语16 小时前
HarmonyOS7 焦点事件实战:onFocus、onBlur 与走焦控制(附完整案例)
harmonyos
钉先生贾16 小时前
HarmonyOS 7.0 性能排障实战 43:图片与大资源加载抖动时,怎样区分解码、布局与状态更新
java·前端·harmonyos
默 语16 小时前
HarmonyOS7 点击事件实战:onClick、ClickEvent 与防误触(附完整案例)
harmonyos
默 语17 小时前
HarmonyOS7 快捷键事件实战:keyboardShortcut 从组合键到功能键(附完整案例)
harmonyos
我闪了个去18 小时前
给联系人存农历生日,App 里也能做了:HarmonyOS 7 联系人 SignificantDate 上手,附“今年哪天过生日”换算模板
harmonyos·arkts
OH_TPC18 小时前
@ohos/ffmpeg-kit 源码解读(一):aki 绑定层与线程模型——JSBIND 注册、线程池与跨线程回调
harmonyos
码间留白19 小时前
鸿蒙推送偶现静默通知(标题显示 Title、落进更多通知)的定位与修复:区分厂商通道与 TIMPush 本地补发
前端·uniapp·harmonyos·鸿蒙·推送·harmonyos next·push kit·timpush
默 语21 小时前
HarmonyOS7 软键盘事件实战:onNeedSoftkeyboard 与键盘接续(附完整案例)
计算机外设·harmonyos