美文网首页Android代码封装
搭建Flutter-Native混合工程,并集成咸鱼Flutte

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

作者: 漫步者_d40d | 来源:发表于2019-12-27 16:22 被阅读0次

    目录

    一、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、命令行进入项目目录

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

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

    image image.gif

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

    image image.gif

    3、编译android模板项目

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

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

    image image.gif

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

    image image.gif

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

    implementation project(':flutter')
    
    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'
    
    image.gif

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

    9、native端flutter_boost初始化配置

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

    image 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<String, Object> urlParams, int requestCode, Map<String, Object> 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);
        }
    }
    
    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<String, String> 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;
            }
        }
    }
    
    image.gif

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

    public class PageRouter {
    
        public final static Map<String, String> pageName = new HashMap<String, String>() {{
    
            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;
            }
        }
    }
    
    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<StatefulWidget> createState() {
        return _MyAppState();
      }
    }
    
    class _MyAppState extends State<MyApp> {
      @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:$pageName\n params:$params\n route:$route");
      }
    }
    
    
    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<StatefulWidget> createState() {
        return _FlutterRouteWidgetState();
      }
    }
    
    class _FlutterRouteWidgetState extends State<FlutterRouteWidget> {
      @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: <Widget>[
                Container(
                  margin: const EdgeInsets.only(top: 10.0, bottom: 20.0),
                  child: Text(
                    message ??
                        "This is a flutter activity\n 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"}
                  }),
                )
              ],
            ),
          ),
        );
      }
    }
    
    image.gif
    FragmentRouteWidget组件实现,flutter实现的native的Fragment
    
    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: <Widget>[
              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"),
              )
            ],
          ),
        );
      }
    }
    
    image.gif

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

     <!--        这个必须注册,不然无法打开flutter的页面-->
            <activity
                android:name="com.idlefish.flutterboost.containers.BoostFlutterActivity"
                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
                android:hardwareAccelerated="true"
                android:screenOrientation="portrait"
                android:theme="@style/Theme.AppCompat"
                android:windowSoftInputMode="adjustResize">
                <meta-data
                    android:name="io.flutter.embedding.android.SplashScreenDrawable"
                    android:resource="@drawable/page_loading" />
    
            </activity>
    
    image.gif

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

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

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

    image image.gif ​ image image.gif ​ image image.gif

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

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

    相关文章

      网友评论

        本文标题:搭建Flutter-Native混合工程,并集成咸鱼Flutte

        本文链接:https://www.haomeiwen.com/subject/grpdoctx.html