阅读 24

Flutter系列笔记-10:安卓flutter混合开发之2 FlutterBoost集成体验

什么是FlutterBoost

​ 新一代Flutter-Native混合解决方案。 FlutterBoost是一个Flutter插件,它可以轻松地为现有原生应用程序提供Flutter混合集成方案。FlutterBoost的理念是将Flutter像Webview那样来使用。在现有应用程序中同时管理Native页面和Flutter页面并非易事。 FlutterBoost帮你处理页面的映射和跳转,你只需关心页面的名字和参数即可(通常可以是URL)。

开发环境

flutter和flutter boost版本有很多,技术不断发展,以官方最新版本为准

Flutter 1.12.13+hotfix.5 • channel stable • github.com/flutter/flu… Framework • revision 27321ebbad (3 months ago) • 2019-12-10 18:15:01 -0800 Engine • revision 2994f7e1e6 Tools • Dart 2.7.0

AndroidStudio 3.6

flutter-boost版本 task/task_v1.12.13_support_hotfixes,不支持androidx

引入依赖和配置flutterboost

FlutterBoost是flutter混合开发时使用的库,引入依赖时,你需要新建一个安卓工程,并把flutter作为一个安卓工程的子模块引入,安卓flutter混合工程配置请看Flutter系列笔记-9:Android原生Flutter混合编程

flutter_module配置

打开flutter_module子工程,先在 pubspec.yaml 里加入

flutter_boost:
  git:
    url: 'https://github.com/alibaba/flutter_boost.git'
    ref: 'task/task_v1.12.13_support_hotfixes'
复制代码

完整如下

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  flutter_boost:
    git:
      url: 'https://github.com/alibaba/flutter_boost.git'
      ref: 'task/task_v1.12.13_support_hotfixes'
复制代码

添加完成后,执行 Packages get

安卓工程配置

执行完后,切换到安卓工程,在app/build.gradle里添加依赖

implementation project(':flutter_boost')
复制代码

完整如下

dependencies {
    implementation project(':flutter')
    implementation project(':flutter_boost')
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
复制代码

同步一下工程。依赖配置成功。

安卓工程初始化FlutterBoost配置

在安卓工程的Application的onCreate方法初始化 flutter boost

public class MyApplication extends Application {
    public final static String TAG = "flutterBoostApplication";

    @Override
    public void onCreate() {
        super.onCreate();

        INativeRouter router = new INativeRouter() {
            @Override
            public void openContainer(Context context, String url, Map<String, Object> urlParams, int requestCode, Map<String, Object> exts) {
                Log.d(TAG,"openContainer url:"+url+"\turlParams:"+urlParams+"\trequestCode:"+requestCode+"\texts:"+exts);
                String assembleUrl = Utils.assembleUrl(url, urlParams);
                PageRouter.openPageByUrl(context, assembleUrl, urlParams);
            }

        };

        FlutterBoost.BoostLifecycleListener boostLifecycleListener = new FlutterBoost.BoostLifecycleListener() {

            @Override
            public void beforeCreateEngine() {
                Log.d(TAG,"beforeCreateEngine");
            }

            @Override
            public void onEngineCreated() {
                Log.d(TAG,"onEngineCreated");
            }

            @Override
            public void onPluginsRegistered() {
                Log.d(TAG,"onPluginsRegistered");
            }

            @Override
            public void onEngineDestroy() {
                Log.d(TAG,"onEngineDestroy");
            }

        };

        //
        // AndroidManifest.xml 中必须要添加 flutterEmbedding 版本设置
        //
        //   <meta-data android:name="flutterEmbedding"
        //               android:value="2">
        //    </meta-data>
        // GeneratedPluginRegistrant 会自动生成 新的插件方式&emsp;
        //
        //
        Platform platform = new FlutterBoost
                .ConfigBuilder(this, router)
                .isDebug(true)
                .whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
                .renderMode(FlutterView.RenderMode.texture)
                .lifecycleListener(boostLifecycleListener)
                .build();

        FlutterBoost.instance().init(platform);


    }
}
复制代码

app/src/main/AndroidManifest.xml里配置com.idlefish.flutterboost.containers.BoostFlutterActivity

<activity
    android:name="com.idlefish.flutterboost.containers.BoostFlutterActivity"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
    android:hardwareAccelerated="true"
    android:theme="@style/Theme.AppCompat"
    android:windowSoftInputMode="adjustResize">
    <meta-data
        android:name="io.flutter.embedding.android.SplashScreenDrawable"
        android:resource="@drawable/page_loading" />

</activity>
复制代码

flutter_module里初始化flutterboost配置

主要是

FlutterBoost.singleton.registerPageBuilders方法 注册页面路由用

FlutterBoost.singleton.addBoostNavigatorObserver(TestBoostNavigatorObserver());路由生命周期回调

MaterialApp里的 builder: FlutterBoost.init(postPush: _onRoutePushed),

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();

    FlutterBoost.singleton.registerPageBuilders({
      'embeded': (pageName, params, _)=>EmbededFirstRouteWidget(),
      'first': (pageName, params, _) => FirstRouteWidget(),
      'second': (pageName, params, _) => SecondRouteWidget(),
      'tab': (pageName, params, _) => TabRouteWidget(),
      'platformView': (pageName, params, _) => PlatformRouteWidget(),
      'flutterFragment': (pageName, params, _) => FragmentRouteWidget(params),
      ///可以在native层通过 getContainerParams 来传递参数
      'flutterPage': (pageName, params, _) {
        print("flutterPage params:$params");

        return FlutterRouteWidget(params:params);
      },
    });
    FlutterBoost.singleton.addBoostNavigatorObserver(TestBoostNavigatorObserver());
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Boost example',
        builder: FlutterBoost.init(postPush: _onRoutePushed),
        home: Container(
            color:Colors.white
        ));
  }

  void _onRoutePushed(
      String pageName, String uniqueId, Map params, Route route, Future _) {
  }
}
复制代码

安卓页面里打开安卓页面

使用普通的startActivity即可

context.startActivity(new Intent(context, NativePageActivity.class));
复制代码

安卓原生页面里打开flutter页面

url为 flutter_module里FlutterBoost.singleton.registerPageBuilders里配置的页面路由,

params 是原生要传给flutter页面的参数集合

backgroundMode 有两种opaque(不透明)和transparent(透明)两种

//打开flutter页面
Intent intent = BoostFlutterActivity.withNewEngine().url(pageName.get(path)).params(params)
        .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context);
if(context instanceof Activity){
    Activity activity=(Activity)context;
    activity.startActivityForResult(intent,requestCode);
}else{
    context.startActivity(intent);
}
复制代码

flutter页面打开安卓原生页面

FlutterBoost.singleton
    .open("sample://nativePage", urlParams: {
  "query": {"aaa": "bbb"}
})
复制代码

需要指定url和urlParams,

FlutterBoost.singleton.open方法实际上是对应执行安卓代码的 INativeRouter的openContainer方法,原生根据参数按需要使用startActivity打开原生页面

INativeRouter router = new INativeRouter() {
    @Override
    public void openContainer(Context context, String url, Map<String, Object> urlParams, int requestCode, Map<String, Object> exts) {

    }
};
复制代码

flutter页面使用FlutterBoost打开flutter页面

flutter打开flutter页面(widget)可以使用flutter里普通的路由管理Navigator.push或Navigator.pushName,也可以用FlutterBoost.singleton.open打开一个flutter页面

FlutterBoost.singleton.open("second").then((Map value) {
  print(
      "call me when page is finished. did recieve second route result $value");
})
复制代码

flutter页面关闭FlutterBoost.singleton.open打开的flutter页面,并返回值给前一个页面

BoostContainerSettings settings =BoostContainer.of(context).settings;
FlutterBoost.singleton.close(settings.uniqueId,result: {"result": "data from second"});
复制代码

安卓原生页面里使用flutterboost的FlutterFragment的使用

flutterboost的FlutterFragment和安卓的Fragment差不多

com.idlefish.flutterboost.containers.FlutterFragment这个FlutterFragment和flutter官方的io.flutter.embedding.android.FlutterFragment不是同一个

FlutterFragment mFragment = new FlutterFragment.NewEngineFragmentBuilder().url("flutterFragment").build()
复制代码

使用NewEngineFragmentBuilder创建了FlutterFragment之后,按普通的Fragment使用即可。一般还配合SplashScreenProvider使用,以避免白屏。

flutter页面显示原生控件

暂未整理

项目地址体验地址: FlutterBoostExample

关注下面的标签,发现更多相似文章
评论