Android原生跳转到Flutter页面
1.启动Flutter页面 默认界面
startActivity( FlutterActivity.withNewEngine().build(activity!!) )
2.启动Flutter指定的界面比如设置界面
Android 中
startActivity( FlutterActivity .withNewEngine() .initialRoute("/setting") .build(activity!!))
Flutter中 需要注册路由
遇到的问题,启动Flutter页面比较缓慢,优化
思路:在Application中提前初始化FlutterEngine 进行缓存 从缓存中取FlutterEngine进行启动
fun registerEngine(routerName: String,context: Context) { val engine = FlutterEngine(context) engine.navigationChannel.setInitialRoute(routerName) engine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) FlutterEngineCache.getInstance().put(routerName,engine) }
从缓存中获取
fun getEngine(routerName: String,context: Context) : Intent { return FlutterActivity.withCachedEngine(routerName).build(context) }
封装后:
package com.bestarschool.parent.util import android.content.Context import android.content.Intent import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngineCache import io.flutter.embedding.engine.dart.DartExecutor object EngineManager { // 保存 fun registerEngine(routerName: String,context: Context) { val engine = FlutterEngine(context) engine.navigationChannel.setInitialRoute(routerName) engine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) FlutterEngineCache.getInstance().put(routerName,engine) } // 获取intent fun getEngine(routerName: String,context: Context) : Intent { return FlutterActivity.withCachedEngine(routerName).build(context) } }
调用启动Flutter RouteManager.setting 为路由名称 /setting
startActivity( EngineManager.getEngine(RouteManager.setting,activity!!) )
问题:新启动的页面没有返回上一页按钮,但是项目中需要有返回按钮如何解决:思路如下
Scaffold( appBar: AppBar( leading: IconButton( onPressed: () { // 退出 flutter 页面 Navigator.pop(); }, icon: Icon(Icons.arrow_back)), title: Text("设置页面"), centerTitle: true, )
这样写的问题 退出后停留在黑屏界面并没有完全退出,解决方案,调用 SystemNavigator.pop();
Scaffold( appBar: AppBar( leading: IconButton( onPressed: () { // 退出所有 flutter 页面 SystemNavigator.pop(); }, icon: Icon(Icons.arrow_back)), title: Text("设置页面"), centerTitle: true, )
点击返回按钮能正常退出了,但是点击手机的返回键仍不能完全退出flutter页面,解决办法 ,去掉home 是我自己用法错误