目录

一、Flutter_Boost是什么

二、准备工作

三、已经有Native项目

1、命令行进入项目目录

2、运行:flutter create -t module flutter_lib命令,flutter_lib这个名字自己起,代表flutter module的名称,运行完毕如下图。

3、编译android模板项目

4、在native项目的app的 build.gradle文件中添加 java8的支持

5、在native项目的settings.gradle文件中增加如下配置,关联flutter_lib,重点是要配置include_flutter.groovy文件的路劲,添加完毕后同步项目

6、native的app的build.gradle文件中添加flutter依赖并同步

7、添加flutter-boost,在flutter_lib的pubspec.yaml文件中添加如下依赖,这里是根据flutter_boost的github文档添加

8、检查链接是否正确,使用:flutter build apk命令检查是否完成flutter_boost和其他库的依赖,如果出现错误根据错误解决所有错误直到编译成功为止。9、native端flutter_boost初始化配置

Flutter-boost是咸鱼开源的一个flutter插件,是一个flutter-native混合开发解决方案,今天聊一聊flutter-boost如何集成到android原生项目

一、Flutter_Boost是什么

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

二、准备工作

1、flutter sdk 的版本需要 v1.9.1-hotfixes分支,否则会编译失败.

2、原生项目最好先换成support库,androidx会出现意想不到的问题

3、保证flutter的运行环境正常

三、已经有Native项目

1、命令行进入项目目录

frc 6380adcbc85cd2aeb9ec2d670e3ebf12 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
frc a9f739ab99bf4774bb58436faae9110b - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

2、运行:flutter create -t module flutter_lib命令,flutter_lib这个名字自己起,代表flutter module的名称,运行完毕如下图。

frc 014191f61ad9860b42a0cb19867c1045 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc 4b8f3231ff11a1c6b4f1d8d7ce595add - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

这个时候你的native工程下会出现一个“flutter_lib”的目录,如下图

frc 8cee86154d677503606a3dd23c22848a - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc 41ebdbefb0182f5caf53e1fa557984c3 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

3、编译android模板项目

命令行进入 “.android”目录下,执行“gradlew flutter:assembleDebug”命令,运行完毕后会在 .android/Flutter/build/outputs/aar/目录下生成flutter-debug.aar

4、在native项目的app的 build.gradle文件中添加 java8的支持

frc a89c71c19e25a15fb794869b4d4bb903 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc 28a8ae2e8a56f9ac606af6c534fc6697 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

5、在native项目的settings.gradle文件中增加如下配置,关联flutter_lib,重点是要配置include_flutter.groovy文件的路劲,添加完毕后同步项目

frc 0daaa10bf54dfd09333243e73b23493d - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc 2b3daf17e537e92ce54644f2904b9816 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

6、native的app的build.gradle文件中添加flutter依赖并同步

implementation project(':flutter')
frc 231ad5b7234da79fa16bfd256eca637c - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

7、添加flutter-boost,在flutter_lib的pubspec.yaml文件中添加如下依赖,这里是根据flutter_boost的github文档添加

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_boost:
    git:
      url: 'https://github.com/alibaba/flutter_boost.git'
      ref: '0.1.60'
frc 66ae2a7d6acc4f4bda0a1c990d6d06f2 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

8、检查链接是否正确,使用:flutter build apk命令检查是否完成flutter_boost和其他库的依赖,如果出现错误根据错误解决所有错误直到编译成功为止。

9、native端flutter_boost初始化配置

第一步:app的build.gradle文件中添加flutter_boost依赖

frc e04b5e2470336bbc9407912ed4ca6220 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc 33ddedac8e054dc99e02badc1e2cbfca - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

第二步:自定义Application并在onCreate中初始化flutter_boost

public class MyApplication extends Application {
    private final static String TAG = MyApplication.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        //路由,Flutter 启动Native页面的时候回调这里
        INativeRouter router = new INativeRouter() {
            @Override
            public void openContainer(Context context, String url, Map urlParams, int requestCode, Map exts) {
                Log.i(TAG, "路由--INativeRouter:url=" + url);
                Log.i(TAG, "路由--INativeRouter:requestCode=" + requestCode);
                Log.i(TAG, "路由--INativeRouter:urlParams=" + urlParams);
                Log.i(TAG, "路由--INativeRouter:exts=" + exts);

                String assembleUrl = Utils.assembleUrl(url, urlParams);
                PageRouter.openPageByUrl(context, assembleUrl, urlParams);
            }
        };
        //插件注册
        FlutterBoost.BoostPluginsRegister pluginsRegister = new FlutterBoost.BoostPluginsRegister() {
            @Override
            public void registerPlugins(PluginRegistry mRegistry) {
                GeneratedPluginRegistrant.registerWith(mRegistry);
                //注册native的TextView插件,插件名称:TextPlatformViewPlugin
                TextPlatformViewPlugin.register(mRegistry.registrarFor("TextPlatformViewPlugin"));
            }
        };
        //配置
        Platform platform = new FlutterBoost.ConfigBuilder(this, router)
                .isDebug(true)
                .whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
                .renderMode(FlutterView.RenderMode.texture)
                .pluginsRegister(pluginsRegister)
                .build();

        //初始化flutter_boost
        FlutterBoost.instance().init(platform);
    }
}
frc 8328da473f90ced7e63df9d0411a5f43 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

第三步:在Native的Activity中编写调用代码,native调用flutter,通过传入url和params打开对应的Flutter widget

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnOpenNative;
    private Button btnOpenFlutter;
    private Button btnOpenFlutterFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnOpenNative = findViewById(R.id.btnOpenNativePage);
        btnOpenFlutter = findViewById(R.id.btnOpenFlutterPage);
        btnOpenFlutterFragment = findViewById(R.id.btnOpenFlutterFragment);

        btnOpenNative.setOnClickListener(this);
        btnOpenFlutter.setOnClickListener(this);
        btnOpenFlutterFragment.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Map params = new HashMap();
        params.put("test1", "v_test1");
        params.put("test2", "v_test2");
        switch (v.getId()) {
            case R.id.btnOpenNativePage:
                PageRouter.openPageByUrl(this, PageRouter.NATIVE_PAGE_URL, params);
                break;
            case R.id.btnOpenFlutterPage:
                //打开一个flutter页面
                PageRouter.openPageByUrl(this, PageRouter.FLUTTER_PAGE_URL, params);
                break;
            case R.id.btnOpenFlutterFragment:
                //打开一个flutter创建的fragment的activity原生page
                PageRouter.openPageByUrl(this, PageRouter.FLUTTER_FRAGMENT_PAGE_URL, params);
                break;
        }
    }
}
frc f2013b95ab4e29b46aebaa096b081503 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

页面路由控制的辅助类PageRouter的实现,它负责管理Native到Flutter的路由调用以及Flutter调用Native的路由

public class PageRouter {

    public final static Map pageName = new HashMap() {{

        put("first", "first");
        put("second", "second");
        put("tab", "tab");
        put("sample://flutterPage", "flutterPage");
    }};

    public static final String NATIVE_PAGE_URL = "sample://nativePage";
    public static final String FLUTTER_PAGE_URL = "sample://flutterPage";
    public static final String FLUTTER_FRAGMENT_PAGE_URL = "sample://flutterFragmentPage";

    public static boolean openPageByUrl(Context context, String url, Map params) {
        return openPageByUrl(context, url, params, 0);
    }

    public static boolean openPageByUrl(Context context, String url, Map params, int requestCode) {

        String path = url.split("\?")[0];

        Log.i("openPageByUrl", path);

        try {
            if (pageName.containsKey(path)) {
                //打开指定url的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);
                }
                return true;
            } else if (url.startsWith(FLUTTER_FRAGMENT_PAGE_URL)) {
                //打开flutter创建的fragment
                context.startActivity(new Intent(context, FlutterFragmentPageActivity.class));
                return true;
            } else if (url.startsWith(NATIVE_PAGE_URL)) {
                //打开原生Activity
                context.startActivity(new Intent(context, NativePageActivity.class));
                return true;
            }
            return false;
        } catch (Throwable t) {
            return false;
        }
    }
}
frc 2d0cd5576104b57478304508bf73c5b5 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

Flutter侧代码实现,在flutter侧直接实现对应的Widget,最后根据路由pageName将其返回给native即可

import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_lib/page_widgets.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State createState() {
    return _MyAppState();
  }
}

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

    ///FlutterBoost注册,给Native返回Flutter的pageWidget
    FlutterBoost.singleton.registerPageBuilders({
      'flutterFragment': (pageName, params, _) => FragmentRouteWidget(params),

      ///可以在native层通过 getContainerParams 来传递参数
      'flutterPage': (pageName, params, _) {
        print("flutterPage params:$params");
        return FlutterRouteWidget(params: params);
      },
    });
  }

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

  ///
  /// 当Native调用flutter widget时回调
  ///
  void _onRoutePushed(
      String pageName, String uniqueId, Map params, Route route, Future _) {
    print("flutter端路由:pageName:$pageNamen params:$paramsn route:$route");
  }
}

frc d3b00164e8f7aa9efad2215c4dd048ee - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

FlutterRouteWidget组件实现,一个flutter实现的native Activity页面

///
/// flutter提供给native的页面widget
///
class FlutterRouteWidget extends StatefulWidget {
  //构造方法,接受native传递的参数
  FlutterRouteWidget({this.params, this.message});

  final Map params;
  final String message;

  @override
  State createState() {
    return _FlutterRouteWidgetState();
  }
}

class _FlutterRouteWidgetState extends State {
  @override
  Widget build(BuildContext context) {
    final String message = widget.message;
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        textTheme: new TextTheme(title: TextStyle(color: Colors.black)),
        title: Text('flutter_boost_example'),
      ),
      body: Container(
        margin: const EdgeInsets.all(24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: const EdgeInsets.only(top: 10.0, bottom: 20.0),
              child: Text(
                message ??
                    "This is a flutter activityn params:${widget.params}",
                style: TextStyle(fontSize: 28.0, color: Colors.blue),
              ),
              alignment: AlignmentDirectional.center,
            ),
            InkWell(
              child: Container(
                padding: const EdgeInsets.all(8.0),
                margin: const EdgeInsets.all(8.0),
                color: Colors.yellow,
                child: Text(
                  'open native page',
                  style: TextStyle(fontSize: 22.0, color: Colors.black),
                ),
              ),

              ///点击事件,打开Native
              ///后面的参数会在native的IPlatform.startActivity方法回调中拼接到url的query部分。
              ///例如:sample://nativePage?aaa=bbb
              onTap: () => FlutterBoost.singleton
                  .open("sample://nativePage", urlParams: {
                "query": {"aaa": "bbb"}
              }),
            )
          ],
        ),
      ),
    );
  }
}
frc 577679cb0abb7b91eb884711d2e2cab9 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif
FragmentRouteWidget组件实现,flutter实现的native的Fragment
frc c9ce0e12effad73ba505826162caf162 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif
///
/// flutter实现的fragment
///
class FragmentRouteWidget extends StatelessWidget {
  FragmentRouteWidget(this.params);

  final Map params;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('flutter_boost_example'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(top: 80.0),
            child: Text(
              "This is a flutter fragment",
              style: TextStyle(fontSize: 28.0, color: Colors.blue),
            ),
            alignment: AlignmentDirectional.center,
          ),
          InkWell(
            child: Container(
                padding: const EdgeInsets.all(8.0),
                margin: const EdgeInsets.all(8.0),
                color: Colors.yellow,
                child: Text(
                  'open native page',
                  style: TextStyle(fontSize: 22.0, color: Colors.black),
                )),
            onTap: () => FlutterBoost.singleton.open("sample://nativePage"),
          )
        ],
      ),
    );
  }
}
frc fc2c506e394dfbdc94b39e5539695c60 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

第四步:AndroidMenifest文件的配置,注册BoostFlutterActivity,这个类必须注册不然无法启动Flutter Widget,在所有需要启动Flutter Widget的Activity注册时都需要加入 :android:hardwareAccelerated=”true”这个属性。

 
        
frc 0eedaaf5bb4f58484ee8d85cc8d38495 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

以上步骤都走完之后就可以编译运行了,本次的重点在于讲解Native项目怎么样集成flutter并引入Flutter_boost,关于flutter_boost的具体用法后面会推出。

最后贴出我最终运行后的结果图:

图1 点击 “打开Flutter页面”—->图2,点击“open native page” —–>图3

frc 5bd87e5ad2c9ba0f11ea4e4e9bf92ff6 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc ca7905c43b1e44fe7a185290415f3c6a - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

frc 35ff8b95437184d7b3820c2ae5eda6fa - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc ba14b9c6f869839f52c72bea8edbbe1e - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

frc 11ff34ec66a71bfd66980f417cf9d9d0 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image
frc e97e1ef51ccd66e7371e5e4a47295395 - 搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost
image.gif

我的博客:https://blog.csdn.net/qq_19979101

flutter-boot搭建flutter混合项目:https://blog.csdn.net/qq_19979101/article/details/103777979

搭建Flutter-Native混合工程,并集成咸鱼Flutter_boost