使用MethodChannel,Android和Flutter互

2024-02-26  本文已影响0人  努力生活的西鱼
一. Android跳转到Flutter
1. 继承FlutterFragmentActivity,并构建Intent
class NewHouseMainActivity : FlutterFragmentActivity() {

    // 通道
    private lateinit var methodChannel: MethodChannel

    companion object {

        private const val EXTRA_INITIAL_ROUTE = "route"

        private const val EXTRA_BACKGROUND_MODE = "background_mode"

        private const val EXTRA_DESTROY_ENGINE_WITH_ACTIVITY = "destroy_engine_with_activity"

        /**
         * 构建Intent
         */
        fun buildIntent(context: Context,routeName: String): Intent {
            return Intent(context,NewHouseMainActivity::class.java)
                .putExtra(EXTRA_INITIAL_ROUTE,routeName)
                .putExtra(EXTRA_BACKGROUND_MODE, FlutterActivityLaunchConfigs.BackgroundMode.opaque.name)
                .putExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, true);
        }

    }
}
2. 启动Activity,组件Intent
val intent = NewHouseMainActivity.buildIntent(
    requireActivity(),
    FlutterRouteBean().createRoute(requireContext(),FlutterParam.rout_new_house)
)
startActivity(intent)
3. 在Flutter端接收
void main() {
  runApp(MyApp(homeRouteName: window.defaultRouteName));
}

Map<String, dynamic> data = convert.jsonDecode(homeRouteName!);
String? routeName = data['routeType'];

switch (routeName) {
    case '/':
    case '/excelSearchPage':
    ...
}

上面的代码写完,就可以成功的跳转到Flutter页面了

二. Flutter跳转到Android
1. 在Flutter和Android端创建通道
class NativeChannel {

  static MethodChannel methodChannel = const MethodChannel("flutter_native");

  // 调用Android原生的方法
  static Future<void> nativeMethod(String method) async {
    await methodChannel.invokeMethod(method);
  }

}


override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    methodChannel = MethodChannel(flutterEngine.dartExecutor,FlutterParam.channel_name)
    methodChannel.setMethodCallHandler { call, result ->
        when (call.method) {
            "toHomePage" -> {
                startActivity(Intent(this,MainActivity::class.java))
            }
        }
    }
}
2. 在Flutter中调用Android方法
onTap: () => {
   NativeChannel.nativeMethod("toHomePage")
},
上一篇下一篇

猜你喜欢

热点阅读