Flutter Boost的router管理

Posted android小菜比

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter Boost的router管理相关的知识,希望对你有一定的参考价值。

环境

FlutterBoost介绍
咸鱼Flutter Boost介绍

Flutter Boost Github

混合开发环境搭建

原生Android集成Flutter混合开发

Flutter SDK版本:

v1.9.1

Flutter Boost 版本:

flutter_boost: ^0.1.63

FlutterBoost集成

FlutterBoost是以插件方式的引入到我们的native项目工程的。

混合工程

混合开发流程可以参考:
原生Android集成Flutter混合开发

Flutter module项目集成FlutterBoost

在flutter_boost_module项目的pubspec.yaml文件中添加依赖插件配置

dependencies:
  flutter:
    sdk: flutter

  flutter_boost: ^0.1.63

配置完成后下载依赖插件到本地

flutter packages get

在native原生项目中rebuild工程,即可引入flutter boost插件,引入flutter boost后的代码结构。其中的amap_base_map是引入了地图插件才显示的,如果没有引入地图插件则不会出现该文件。

在native的项目中,在app目录下的build.gradle中添加flutter_boost项目依赖

 implementation project(':flutter_boost')

FlutterBoost使用

Flutter工程开发

在Flutter项目中创建两个测试页面Widget:FirstRouteWidget和SecondRouteWidget。代码参考了flutter_boost的测试代码。
(1)关于onPressed里面的方法调用,其实就是调用flutter_boost的api进行页面的跳转和传递参数。

class FirstRouteWidget extends StatelessWidget 
  static const KEY_FLUTTER_BOOST_FIRST_ROUTE = "flutterbus://flutterWidget_FirstPage";
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text('First Route'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('open amap widget'),
          onPressed: () 
//            print("open second page!");
            FlutterBoost.singleton.open("flutterbus://flutternativePage", urlParams: "test": "flutter to flutter ")
                .then((Map value) print(
                  "call me when page is finished. did recieve second route result $value"););
//            BoostContainerSettings settings = BoostContainer.of(context).settings;
//            FlutterBoost.singleton.close(settings.uniqueId, result: "result": "data from second");
          ,
        ),
      ),
    );
  


class SecondRouteWidget extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () 
            // Navigate back to first route when tapped.
            BoostContainerSettings settings =
                BoostContainer.of(context).settings;
            FlutterBoost.singleton.close(settings.uniqueId,
                result: "result": "data from second");
          ,
          child: Text('Go back with result!'),
        ),
      ),
    );
  

在main.dart中注册注册这两个页面route。
(1)在build方法中初始化Flutter Boost
(2)在initState中注册需要native启动的route。这里的pageName一定要和native启动时配置的一致,否则会找不到对应route。

class _MyAppState extends State<MyApp> 
  @override
  void initState() 
    super.initState();
    FlutterBoost.singleton.registerPageBuilders(
    //fisrt widget
      FirstRouteWidget.KEY_FLUTTER_BOOST_FIRST_ROUTE: (pageName, params, _) 
        debugPrint("params :$params.toString()");
        return FirstRouteWidget();
      ,
      //second widget
      'flutterbus://flutterSecondPage': (pageName, params, _) 
        debugPrint("params :$params.toString()");
        return SecondRouteWidget();
      ,
    );
  

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
        title: 'Flutter Boost example',
        //初始化FlutterBoost
        builder: FlutterBoost.init(postPush: _onRoutePushed),
        home: Container());
  

  void _onRoutePushed(
      String pageName, String uniqueId, Map params, Route route, Future _) 
    debugPrint("pageName :$pageName" + "params :$params.toString()");
  


native项目中使用FlutterBoost

初始化flutter引擎。
(1)Flutter引擎初始化,代码参考Flutter_boost demo.
(2)INativeRouter接口需要注意,不仅通过flutter启动native页面会调用该方法,而且通过flutter会用flutter页面,也会执行该方法。
(3)在Application中调用FlutterBootManager.init()方法完成初始化。
(4)NativePageRouter在启动route会用到。可以自行封装。


object FlutterBootManager 
    fun init(app: Application) 
        /**
         * 不仅打开Native页面会执行,在Flutter页面打开Flutter  widget也会执行该方法
         **/
        val router = INativeRouter  context, url, urlParams, requestCode, exts ->
            val assembleUrl = Utils.assembleUrl(url, urlParams)
            Timber.e("native open :$url $urlParams")
            NativePageRouter.openPageByUrl(context, assembleUrl, requestCode)
        

        val pluginsRegister = object : FlutterBoost.BoostPluginsRegister 

            override fun registerPlugins(mRegistry: PluginRegistry?) 
                GeneratedPluginRegistrant.registerWith(mRegistry)
                TextPlatformViewPlugin.register(mRegistry?.registrarFor("TextPlatformViewPlugin"))
            
        

        val platform = FlutterBoost.ConfigBuilder(app, router)
                .isDebug(BuildConfig.DEBUG)
                .whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
                .renderMode(FlutterView.RenderMode.texture)
                .pluginsRegister(pluginsRegister)
                .build()

        FlutterBoost.instance().init(platform)
    

配置Flutter页面对应的Native容器。

 <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">

页面跳转route

页面路由跳转我把它分成了三种情况,下面说说每中情况的代码实现。
一、native启动flutter
(1)不携带参数:
在native测可以通过BoostFlutterActivity通过构建者模式构建一个intent。BoostFlutterActivity要注册在manifest文件中。

companion object 
        const val FLUTTER_FIRST_PAGE_URL = "flutterbus://flutterWidget_FirstPage"
    

    override fun openFlutterWidget(context: Context, params: HashMap<String,Any>?): Boolean 
        try 
            val intent = BoostFlutterActivity.withNewEngine().url(FLUTTER_FIRST_PAGE_URL)
                    .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context)
            context.startActivity(intent)
            return true
         catch (e: Exception) 
            return false
        
    

在flutter module中打印出请求的url,和params。

 FirstRouteWidget.KEY_FLUTTER_BOOST_FIRST_ROUTE: (pageName, params, _) 
        debugPrint("params :$params.toString()");
        return FirstRouteWidget();
      

(2)携带请求参数
flutter module代码不变。

companion object 
        const val FLUTTER_FIRST_PAGE_URL = "flutterbus://flutterWidget_FirstPage"
    

    override fun openFlutterWidget(context: Context, params: HashMap<String,Any>?): Boolean 
        try 
            var params = mutableMapOf<String,Any>()
            params["str"] = "flutter boost"
            params["in"] = 1
            val intent = BoostFlutterActivity.withNewEngine().url(FLUTTER_FIRST_PAGE_URL).params(params)
                    .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context)
            context.startActivity(intent)
            return true
         catch (e: Exception) 
            return false
        
    

(3)获取flutter的处理结果。
在native测通过startActivityForResult启动flutter container。

override fun openFlutterWidgetForResult(activity: BaseActivity, params: HashMap<String,Any>?, requestCode: Int): Boolean 
        try 
            var params = mutableMapOf<String,Any>()
            params["str"] = "flutter boost"
            params["in"] = 1
            val intent = BoostFlutterActivity.withNewEngine().url(FLUTTER_FIRST_PAGE_URL).params(params)
                    .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(activity)

            activity.startActivityForResult(intent, requestCode)
            return true
         catch (e: Exception) 
            return false
        
    

在当前activity的onActivityResult获取请求结果
注意这里的KEY值,这个值是定值,不可修改。并且在flutter获取native的返回值是也需要用到该值。

 REQUEST_CODE -> 
                Timber.e("flutter data :"+data?.extras?.get(IFlutterViewContainer.RESULT_KEY))
            


在flutter module通过FlutterBoost的close方法,把处理结果返回给上一个页面。

  BoostContainerSettings settings = BoostContainer.of(context).settings;
  FlutterBoost.singleton.close(settings.uniqueId, result: "result": "data from second");

最终native获取的返回值格式:

flutter data :result=data from second

二、flutter启动flutter
(1)直接启动,不携带参数
注意;这里还需要在native层进行实现,才能最终启动flutter route,因为flutter route需要一个native容器。

FlutterBoost.singleton.open("flutterbus://flutterSecondPage");

在native的FlutterBootManager中有个INativeRouter接口的实现类,在给INativeRouter的openContainer方法中,能获取到启动的url,请求参数urlParams、和requestCode和当前的activity的上下问context。
在openContainer方法中,在调用启动**“native启动flutter”**的相关方法,启动flutter route。
例如:

 val intent = BoostFlutterActivity.withNewEngine().url(NATIVE_FIRST_PAGE_URL)
                        .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context)
                if(context is Activity)
                    (context as Activity).startActivityForResult(intent,0x13)
                

(2)携带参数启动

FlutterBoost.singleton.open("flutterbus://flutterSecondPage", urlParams: "test": "flutter to flutter ")

(3)获取返回值
在first route通过如下代码启动second route

FlutterBoost.singleton.open("flutterbus://flutternativePage", urlParams: "test": "flutter to flutter ")
                .then((Map value) print(
                  "call me when page is finished. did recieve second route result $value"););

在second通过如下代码关闭当前页面,并返回处理的数据

BoostContainerSettings settings =
                BoostContainer.of(context).settings;
            FlutterBoost.singleton.close(settings.uniqueId,
                result: "result": "data from second");

三、flutter 启动native页面
(1)直接启动,不带参数

FlutterBoost.singleton.open("flutterbus://flutternativePage");

在native的FlutterBootManager中有个INativeRouter接口的实现类,在给INativeRouter的openContainer方法中,能获取到启动的url,请求参数urlParams、和requestCode和当前的activity的上下问context。
在openContainer方法中,在调用启动startActivity的相关方法,启动native route。
例如

 var intent = Intent(context,FlutterOpenNativeTestActivity::class.java)
                if(context is Activity)
                    (context as Activity).startActivityForResult(intent,requestCode)
                

(2)携带请求参数
在INativeRouter的openContainer方法,可以获取到请求的参数。
这里的请求最终会执行到native的INativeRouter 实现类。

FlutterBoost.singleton.open("flutterbus://flutternativePage", urlParams: "test": "flutter to flutter ")

(3)获取返回值
flutter 的代码实现

FlutterBoost.singleton.open("flutterbus://flutternativePage", urlParams: "test": "flutter to flutter ")
                .then((Map value) print(
                  "call me when page is finished. did recieve second route result $value"););

native的代码实现
注意点:putExtra的key是定值,并且值只能是map。

close_btn.setOnClickListener
            var map = mutableMapOf<String,Any>()
            map.put("native","test native")
            intent.putExtra(IFlutterViewContainer.RESULT_KEY,(map as Serializable))

            setResult(Activity.RESULT_OK,intent)
            finish()
        

四、native启动native
和原生开发没有区别。

PS:主要点不是flutter_boost的API使用,而是获取返回值的阅读官方demo遇到的坑,demo写的不够全面,一些常见的场景都没有覆盖。

以上是关于Flutter Boost的router管理的主要内容,如果未能解决你的问题,请参考以下文章

Android & Flutter 相互跳转

2019 最前沿的几个 Flutter 实践:微信咸鱼美团

前端工作2年,因Flutter拿到了阿里咸鱼offer,背后的努力值得我们学习

前端工作2年,因Flutter拿到了阿里咸鱼offer,背后的努力值得我们学习

Flutter Boost 3.0初探

Flutter沉浸式状态栏/AppBar导航栏/仿咸鱼底部凸起导航