当前位置:   article > 正文

Flutter 和 Android原生(Activity、Fragment)相互跳转、传参_flutter跳转原生activity

flutter跳转原生activity

前言

本文主要讲解 Flutter 和 Android原生之间,页面相互跳转、传参,

但其中用到了两端相互通信的知识,非常建议先看完这篇 讲解通信的文章

Flutter 与 Android原生 相互通信:BasicMessageChannel、MethodChannel、EventChannel_flutter eventchannel methodchannel basemessagechan-CSDN博客

当前案例 Flutter SDK版本:3.13.2

Flutter使用多个轻量型引擎,进行混合开发,是从 2.0 开始的,大大的减轻了内存压力;

轻量型引擎开发-官方介绍视频:https://www.youtube.com/watch?v=p6cK_0jp2ag

Flutter和原生端的关系

混合路由栈

如果是纯Flutter开发只会有一个Flutter引擎,如果是混合开发,原生端 需要为每个从原生端跳转的Flutter页面创建独立的引擎 (也可以单例,但单例写法需要处理一些问题,这个到 FlutterEngineGroup 章节会具体讲解);

比如:

1.0 从 Android_A页面  ==== 跳转到 ==== Flutter_A页面,Android端需要为Flutter_A页面,创建Flutter引擎;

1.1 紧接着,从 Flutter_A页面 ==== 跳转到 ==== Flutter_B页面,就不需要,它俩共用一个引擎;

1.2 每个Flutter引擎都有自己的路由栈,且这个路由栈只能管理Flutter页面

1.3 使用Flutter提供的 Navigator.pop(context); 方法,可以从 Flutter_B页面 回退到 Flutter_A页面,但无法从 Flutter_A页面 回退到 Android_A,会黑屏,因为Flutter栈里面没有Android页面,可以使用 Navigator.canPop(context); 来检查Flutter路由栈中,是否还有其他路由;

1.4 如果不使用 Navigator.pop(context); 回退方法,使用手机自带的 Back按键 / 左滑屏幕 进行回退,是没有问题的,因为这种回退方式调用的是原生API,Android原生不光提供FlutterView渲染Flutter页面结果,还会创建FlutterActivityFlutterView进行绑定;

1.5 看到这,大家应该理解,为什么说Flutter只是UI框架了吧;

Android 和 Flutter 跳转

Android 跳转 Flutter

Flutter 跳转 Android

效果图

Android代码

FlutterRouterManager.kt

  1. package com.example.flutter_nav_android.util
  2. import android.app.Activity
  3. import io.flutter.embedding.android.FlutterActivity
  4. import io.flutter.embedding.android.FlutterActivityLaunchConfigs
  5. import io.flutter.embedding.engine.FlutterEngine
  6. import io.flutter.embedding.engine.FlutterEngineCache
  7. import io.flutter.embedding.engine.dart.DartExecutor
  8. class FlutterRouterManager(
  9. val targetRoute: String,
  10. val mEngineId: String,
  11. val mContext: Activity
  12. ) {
  13. var mEngine: FlutterEngine? = null
  14. init {
  15. createCachedEngine()
  16. }
  17. companion object {
  18. /**
  19. * 获取缓存中的 Flutter引擎
  20. */
  21. @JvmStatic
  22. fun getEngineCacheInstance(engineId: String): FlutterEngine? {
  23. return FlutterEngineCache.getInstance().get(engineId)
  24. }
  25. }
  26. /**
  27. * 1、创建Flutter引擎
  28. * 2、将初始命名路由,修改为目标页面路由
  29. * 3、缓存Flutter引擎
  30. */
  31. fun createCachedEngine(): FlutterEngine {
  32. val flutterEngine = FlutterEngine(mContext) // 创建Flutter引擎
  33. // 将初始命名路由,修改为目标页面路由
  34. flutterEngine.navigationChannel.setInitialRoute(targetRoute)
  35. // 这一步,是在执行相关Dart文件入口的 main函数,将Flutter页面渲染出结果
  36. // 原生端获取结果,进行最终渲染上屏
  37. flutterEngine.dartExecutor.executeDartEntrypoint(
  38. DartExecutor.DartEntrypoint.createDefault()
  39. )
  40. // 将加载好的引擎,存储起来
  41. FlutterEngineCache.getInstance().put(mEngineId, flutterEngine)
  42. mEngine = flutterEngine
  43. return flutterEngine
  44. }
  45. /**
  46. * 根据引擎ID,前往指定的Flutter页面
  47. */
  48. fun push() {
  49. // 创建新的引擎(了解即可)
  50. // mContext.startActivity(
  51. // FlutterActivity
  52. // .withNewEngine() // 创建引擎
  53. // .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent) // 背景改为透明,不然切换页面时,会闪烁黑色
  54. // .build(mContext))
  55. // 使用缓存好的引擎(推荐)
  56. mContext.startActivity(
  57. FlutterActivity
  58. .withCachedEngine(mEngineId) // 获取缓存好的引擎
  59. .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent) // 背景改为透明,不然切换页面时,会闪烁黑色
  60. .build(mContext)
  61. )
  62. }
  63. /**
  64. * 销毁当前Flutter引擎
  65. */
  66. fun destroy() {
  67. mEngine?.destroy()
  68. }
  69. }

PersonalActivity.kt

  1. package com.example.flutter_nav_android.ui.activity
  2. import android.graphics.Color
  3. import android.os.Bundle
  4. import android.text.SpannableString
  5. import android.text.Spanned
  6. import android.text.style.ForegroundColorSpan
  7. import android.view.View
  8. import androidx.appcompat.app.AppCompatActivity
  9. import com.example.flutter_nav_android.databinding.ActivityPersonalBinding
  10. import com.example.flutter_nav_android.util.FlutterRouterManager
  11. import io.flutter.embedding.engine.FlutterEngine
  12. import io.flutter.plugin.common.MethodCall
  13. import io.flutter.plugin.common.MethodChannel
  14. class PersonalActivity : AppCompatActivity(), MethodChannel.MethodCallHandler, View.OnClickListener {
  15. private lateinit var bind: ActivityPersonalBinding
  16. private lateinit var homeFlutterEngine: FlutterEngine
  17. private lateinit var loginRouterManager: FlutterRouterManager
  18. private lateinit var loginMethodChannel: MethodChannel
  19. private lateinit var homeMethodChannel: MethodChannel
  20. private val METHOD_CHANNEL_LOGIN = "com.example.flutter_nav_android/login/method"
  21. private val METHOD_CHANNEL_HOME = "com.example.flutter_nav_android/home/method"
  22. private val NAV_FLUTTER_LOGIN_NOTICE = "navFlutterLoginNotice"
  23. private val POP_NOTICE = "popNotice"
  24. private val PERSONAL_POP_NOTICE = "personalPopNotice"
  25. override fun onCreate(savedInstanceState: Bundle?) {
  26. super.onCreate(savedInstanceState)
  27. bind = ActivityPersonalBinding.inflate(layoutInflater)
  28. setContentView(bind.root)
  29. initView()
  30. loginRouterManager = FlutterRouterManager("/login", "login_engine", this)
  31. // 两端建立通信
  32. loginMethodChannel = MethodChannel(loginRouterManager.mEngine!!.dartExecutor, METHOD_CHANNEL_LOGIN)
  33. loginMethodChannel.setMethodCallHandler(this)
  34. // 获取 Flutter Home页面的引擎,并且建立通信
  35. homeFlutterEngine = FlutterRouterManager.getEngineCacheInstance("home_engine")!!
  36. homeMethodChannel = MethodChannel(homeFlutterEngine.dartExecutor,METHOD_CHANNEL_HOME)
  37. }
  38. /**
  39. * 监听来自 Flutter端 的消息通道
  40. *
  41. * call: Android端 接收到 Flutter端 发来的 数据对象
  42. * result:Android端 给 Flutter端 执行回调的接口对象
  43. */
  44. override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
  45. val methodName: String = call.method
  46. when (methodName) { // 销毁 Flutter Login 页面
  47. POP_NOTICE -> {
  48. val age = call.argument<Int>("age")
  49. getResult(age.toString())
  50. loginRouterManager.mEngine!!.navigationChannel.popRoute()
  51. }
  52. else -> {
  53. result.notImplemented()
  54. }
  55. }
  56. }
  57. override fun onClick(v: View?) {
  58. when (v) {
  59. bind.toFlutter -> { // 前往 Flutter Login 页面
  60. val map: MutableMap<String, String> = mutableMapOf<String, String>()
  61. map["name"] = "老王"
  62. loginMethodChannel.invokeMethod(NAV_FLUTTER_LOGIN_NOTICE,map)
  63. loginRouterManager.push()
  64. }
  65. bind.pop -> { // 销毁 Android Personal 页面
  66. val map: MutableMap<String, Int> = mutableMapOf<String, Int>()
  67. map["age"] = 18
  68. homeMethodChannel.invokeMethod(PERSONAL_POP_NOTICE,map)
  69. finish()
  70. }
  71. }
  72. }
  73. /**
  74. * 初始化页面
  75. */
  76. private fun initView() {
  77. bind.toFlutter.setOnClickListener(this)
  78. bind.pop.setOnClickListener(this)
  79. var name = intent.getStringExtra("name")
  80. val title = "接收初始化参数:"
  81. val msg = title + name
  82. val ss = SpannableString(msg)
  83. ss.setSpan(
  84. ForegroundColorSpan(Color.RED),
  85. title.length,
  86. msg.length,
  87. Spanned.SPAN_INCLUSIVE_EXCLUSIVE
  88. )
  89. bind.initV.text = ss
  90. }
  91. /**
  92. * 获取上一页的返回参数
  93. */
  94. private fun getResult(age: String) {
  95. val title = "接收上一页返回参数:"
  96. val msg = title + age
  97. val ss = SpannableString(msg)
  98. ss.setSpan(
  99. ForegroundColorSpan(Color.RED),
  100. title.length,
  101. msg.length,
  102. Spanned.SPAN_INCLUSIVE_EXCLUSIVE
  103. )
  104. bind.resultV.text = ss
  105. }
  106. override fun onDestroy() {
  107. super.onDestroy()
  108. loginRouterManager.destroy()
  109. }
  110. }

SchoolActivity.kt

  1. package com.example.flutter_nav_android.ui.activity
  2. import android.content.Intent
  3. import android.os.Bundle
  4. import androidx.appcompat.app.AppCompatActivity
  5. import com.example.flutter_nav_android.databinding.ActivitySchoolBinding
  6. import com.example.flutter_nav_android.util.FlutterRouterManager
  7. import io.flutter.embedding.android.FlutterFragment
  8. import io.flutter.embedding.android.TransparencyMode
  9. import io.flutter.embedding.engine.FlutterEngineCache
  10. import io.flutter.plugin.common.MethodChannel
  11. class SchoolActivity : AppCompatActivity() {
  12. private lateinit var bind: ActivitySchoolBinding
  13. private lateinit var bookFragment: FlutterFragment
  14. private lateinit var studentFragment: FlutterFragment
  15. private val METHOD_CHANNEL_BOOK = "com.example.flutter_nav_android/book/method"
  16. private val METHOD_CHANNEL_STUDENT = "com.example.flutter_nav_android/student/method"
  17. private val NAV_FLUTTER_BOOK_NOTICE = "navFlutterBookNotice"
  18. private val NAV_FLUTTER_STUDENT_NOTICE = "navFlutterStudentNotice"
  19. override fun onCreate(savedInstanceState: Bundle?) {
  20. super.onCreate(savedInstanceState)
  21. bind = ActivitySchoolBinding.inflate(layoutInflater)
  22. setContentView(bind.root)
  23. initView()
  24. initChannel()
  25. }
  26. /**
  27. * 建立通信
  28. */
  29. private fun initChannel() {
  30. val bookEngine = FlutterRouterManager.getEngineCacheInstance("book_engine")
  31. val bookChannel = MethodChannel(bookEngine!!.dartExecutor,METHOD_CHANNEL_BOOK)
  32. val map: MutableMap<String, String> = mutableMapOf<String, String>()
  33. map["title"] = "Book"
  34. bookChannel.invokeMethod(NAV_FLUTTER_BOOK_NOTICE,map)
  35. val studentEngine = FlutterRouterManager.getEngineCacheInstance("student_engine")
  36. val studentChannel = MethodChannel(studentEngine!!.dartExecutor,METHOD_CHANNEL_STUDENT)
  37. val map2: MutableMap<String, String> = mutableMapOf<String, String>()
  38. map2["title"] = "Student"
  39. studentChannel.invokeMethod(NAV_FLUTTER_STUDENT_NOTICE,map2)
  40. }
  41. /**
  42. * 初始化页面
  43. */
  44. private fun initView() {
  45. bookFragment = FlutterFragment.withCachedEngine("book_engine")
  46. .transparencyMode(TransparencyMode.transparent) // 背景透明,避免切换页面,出现闪烁
  47. .shouldAttachEngineToActivity(false) // 是否让Flutter控制Activity,true:可以 false:不可以,默认值 true
  48. .build()
  49. supportFragmentManager
  50. .beginTransaction()
  51. .add(bind.bookFragment.id, bookFragment)
  52. .commit()
  53. studentFragment = FlutterFragment.withCachedEngine("student_engine")
  54. .transparencyMode(TransparencyMode.transparent) // 背景透明,避免切换页面,出现闪烁
  55. .shouldAttachEngineToActivity(false) // 是否让Flutter控制Activity,true:可以 false:不可以,默认值 true
  56. .build()
  57. supportFragmentManager
  58. .beginTransaction()
  59. .add(bind.studentFragment.id, studentFragment)
  60. .commit()
  61. }
  62. // ================================ 这些是固定写法,Flutter需要这些回调 ================================
  63. override fun onPostResume() {
  64. super.onPostResume()
  65. bookFragment.onPostResume()
  66. studentFragment.onPostResume()
  67. }
  68. override fun onNewIntent(intent: Intent) {
  69. super.onNewIntent(intent)
  70. bookFragment.onNewIntent(intent)
  71. studentFragment.onNewIntent(intent)
  72. }
  73. override fun onBackPressed() {
  74. bookFragment.onBackPressed()
  75. studentFragment.onBackPressed()
  76. }
  77. override fun onRequestPermissionsResult(
  78. requestCode: Int,
  79. permissions: Array<String?>,
  80. grantResults: IntArray
  81. ) {
  82. super.onRequestPermissionsResult(requestCode, permissions, grantResults)
  83. bookFragment.onRequestPermissionsResult(
  84. requestCode,
  85. permissions,
  86. grantResults
  87. )
  88. studentFragment.onRequestPermissionsResult(
  89. requestCode,
  90. permissions,
  91. grantResults
  92. )
  93. }
  94. override fun onUserLeaveHint() {
  95. bookFragment.onUserLeaveHint()
  96. studentFragment.onUserLeaveHint()
  97. }
  98. override fun onTrimMemory(level: Int) {
  99. super.onTrimMemory(level)
  100. bookFragment.onTrimMemory(level)
  101. studentFragment.onTrimMemory(level)
  102. }
  103. }

MainActivity.kt

  1. package com.example.flutter_nav_android.ui.activity
  2. import android.content.Intent
  3. import android.graphics.Color
  4. import android.text.SpannableString
  5. import android.text.Spanned
  6. import android.text.style.ForegroundColorSpan
  7. import android.view.View
  8. import androidx.appcompat.app.AppCompatActivity
  9. import com.example.flutter_nav_android.databinding.ActivityMainBinding
  10. import com.example.flutter_nav_android.util.FlutterRouterManager
  11. import io.flutter.plugin.common.MethodCall
  12. import io.flutter.plugin.common.MethodChannel
  13. class MainActivity : AppCompatActivity(), MethodChannel.MethodCallHandler, View.OnClickListener {
  14. private lateinit var bind: ActivityMainBinding
  15. private lateinit var homeMethodChannel: MethodChannel
  16. private val METHOD_CHANNEL_HOME = "com.example.flutter_nav_android/home/method"
  17. private val NAV_ANDROID_PERSONAL_NOTICE = "navAndroidPersonalNotice"
  18. private val NAV_FLUTTER_HOME_NOTICE = "navFlutterHomeNotice"
  19. private val POP_NOTICE = "popNotice"
  20. private lateinit var homeRouterManager: FlutterRouterManager
  21. private lateinit var bookRouterManager: FlutterRouterManager
  22. private lateinit var studentRouterManager: FlutterRouterManager
  23. override fun onCreate(savedInstanceState: android.os.Bundle?) {
  24. super.onCreate(savedInstanceState)
  25. bind = ActivityMainBinding.inflate(layoutInflater)
  26. setContentView(bind.root)
  27. bind.toFlutter.setOnClickListener(this)
  28. bind.toFlutterFragment.setOnClickListener(this)
  29. homeRouterManager = FlutterRouterManager("/home", "home_engine", this)
  30. // 两端建立通信
  31. homeMethodChannel = MethodChannel(homeRouterManager.mEngine!!.dartExecutor,METHOD_CHANNEL_HOME)
  32. homeMethodChannel.setMethodCallHandler(this)
  33. // 这里Fragment案例的
  34. bookRouterManager = FlutterRouterManager("/book", "book_engine", this)
  35. studentRouterManager = FlutterRouterManager("/student", "student_engine", this)
  36. }
  37. /**
  38. * 监听来自 Flutter端 的消息通道
  39. *
  40. * call: Android端 接收到 Flutter端 发来的 数据对象
  41. * result:Android端 给 Flutter端 执行回调的接口对象
  42. */
  43. override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
  44. val methodName: String = call.method
  45. when (methodName) {
  46. NAV_ANDROID_PERSONAL_NOTICE -> { // Flutter Home 页面 前往 Android Personal 页面
  47. val intent = Intent(this, PersonalActivity::class.java)
  48. intent.putExtra("name",call.argument<String>("name"))
  49. startActivity(intent)
  50. }
  51. POP_NOTICE -> { // 销毁 Flutter Home 页面
  52. val age = call.argument<Int>("age")
  53. getResult(age.toString())
  54. homeRouterManager.mEngine!!.navigationChannel.popRoute()
  55. }
  56. else -> {
  57. result.notImplemented()
  58. }
  59. }
  60. }
  61. override fun onClick(v: View?) {
  62. when (v) {
  63. bind.toFlutter -> { // 前往 Flutter Home 页面
  64. val map: MutableMap<String, String> = mutableMapOf<String, String>()
  65. map["name"] = "张三"
  66. homeMethodChannel.invokeMethod(NAV_FLUTTER_HOME_NOTICE,map)
  67. homeRouterManager.push()
  68. }
  69. bind.toFlutterFragment -> {
  70. val intent = Intent(this, SchoolActivity::class.java)
  71. startActivity(intent)
  72. }
  73. }
  74. }
  75. /**
  76. * 获取上一页的返回参数
  77. */
  78. private fun getResult(age: String) {
  79. val title = "接收上一页返回参数:"
  80. val msg = title + age
  81. val ss = SpannableString(msg)
  82. ss.setSpan(
  83. ForegroundColorSpan(Color.RED),
  84. title.length,
  85. msg.length,
  86. Spanned.SPAN_INCLUSIVE_EXCLUSIVE
  87. )
  88. bind.resultV.text = ss
  89. }
  90. override fun onDestroy() {
  91. super.onDestroy()
  92. homeRouterManager.destroy()
  93. bookRouterManager.destroy()
  94. studentRouterManager.destroy()
  95. }
  96. }

activity_personal.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <layout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto">
  4. <data>
  5. </data>
  6. <androidx.constraintlayout.widget.ConstraintLayout
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent">
  9. <TextView
  10. android:id="@+id/app_bar"
  11. android:layout_width="match_parent"
  12. android:layout_height="60dp"
  13. android:layout_marginBottom="16dp"
  14. android:background="@color/cardview_shadow_start_color"
  15. android:gravity="center_vertical"
  16. android:paddingStart="16dp"
  17. android:text="Android Personal"
  18. android:textColor="@color/material_dynamic_primary60"
  19. android:textSize="26sp"
  20. android:textStyle="bold"
  21. app:layout_constraintLeft_toLeftOf="parent"
  22. app:layout_constraintTop_toTopOf="parent" />
  23. <TextView
  24. android:id="@+id/init_v"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:gravity="center_vertical"
  28. android:text="接收初始化参数:"
  29. android:textColor="@color/material_dynamic_primary60"
  30. android:textSize="20sp"
  31. android:textStyle="bold"
  32. app:layout_constraintBottom_toBottomOf="parent"
  33. app:layout_constraintLeft_toLeftOf="parent"
  34. app:layout_constraintRight_toRightOf="parent"
  35. app:layout_constraintTop_toTopOf="parent" />
  36. <TextView
  37. android:id="@+id/result_v"
  38. android:layout_width="wrap_content"
  39. android:layout_height="wrap_content"
  40. android:layout_marginTop="20dp"
  41. android:text="接收上一页返回参数:"
  42. android:textColor="@color/material_dynamic_primary60"
  43. android:textSize="20sp"
  44. android:textStyle="bold"
  45. app:layout_constraintLeft_toLeftOf="parent"
  46. app:layout_constraintRight_toRightOf="parent"
  47. app:layout_constraintTop_toBottomOf="@id/init_v" />
  48. <Button
  49. android:id="@+id/to_flutter"
  50. android:layout_width="wrap_content"
  51. android:layout_height="wrap_content"
  52. android:layout_marginTop="20dp"
  53. android:text="前往 Flutter Login"
  54. android:textSize="20sp"
  55. android:textAllCaps="false"
  56. app:layout_constraintLeft_toLeftOf="parent"
  57. app:layout_constraintRight_toRightOf="parent"
  58. app:layout_constraintTop_toBottomOf="@id/result_v" />
  59. <Button
  60. android:id="@+id/pop"
  61. android:layout_width="wrap_content"
  62. android:layout_height="wrap_content"
  63. android:layout_marginTop="16dp"
  64. android:text="返回 上一页"
  65. android:textSize="20sp"
  66. android:textAllCaps="false"
  67. app:layout_constraintLeft_toLeftOf="parent"
  68. app:layout_constraintRight_toRightOf="parent"
  69. app:layout_constraintTop_toBottomOf="@id/to_flutter" />
  70. </androidx.constraintlayout.widget.ConstraintLayout>
  71. </layout>

activity_school.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <layout xmlns:android="http://schemas.android.com/apk/res/android">
  3. <data>
  4. </data>
  5. <LinearLayout
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:paddingTop="20dp"
  9. android:orientation="vertical">
  10. <TextView
  11. android:id="@+id/app_bar"
  12. android:layout_width="match_parent"
  13. android:layout_height="60dp"
  14. android:background="@color/cardview_shadow_start_color"
  15. android:gravity="center_vertical"
  16. android:paddingStart="16dp"
  17. android:text="Android School"
  18. android:textColor="@color/material_dynamic_primary60"
  19. android:textSize="26sp"
  20. android:textStyle="bold" />
  21. <FrameLayout
  22. android:id="@+id/book_fragment"
  23. android:layout_weight="1"
  24. android:layout_width="match_parent"
  25. android:layout_height="0dp" />
  26. <FrameLayout
  27. android:id="@+id/student_fragment"
  28. android:layout_weight="1"
  29. android:layout_width="match_parent"
  30. android:layout_height="0dp" />
  31. </LinearLayout>
  32. </layout>

activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <layout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto">
  4. <data>
  5. </data>
  6. <androidx.constraintlayout.widget.ConstraintLayout
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent">
  9. <TextView
  10. android:id="@+id/app_bar"
  11. android:layout_width="match_parent"
  12. android:layout_height="60dp"
  13. android:layout_marginBottom="16dp"
  14. android:background="@color/cardview_shadow_start_color"
  15. android:gravity="center_vertical"
  16. android:paddingStart="16dp"
  17. android:text="Android Main"
  18. android:textColor="@color/material_dynamic_primary60"
  19. android:textSize="26sp"
  20. android:textStyle="bold"
  21. app:layout_constraintLeft_toLeftOf="parent"
  22. app:layout_constraintTop_toTopOf="parent" />
  23. <TextView
  24. android:id="@+id/result_v"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:gravity="center_vertical"
  28. android:text="接收上一页返回参数:"
  29. android:textColor="@color/material_dynamic_primary60"
  30. android:textSize="20sp"
  31. android:textStyle="bold"
  32. app:layout_constraintLeft_toLeftOf="parent"
  33. app:layout_constraintTop_toTopOf="parent"
  34. app:layout_constraintRight_toRightOf="parent"
  35. app:layout_constraintBottom_toBottomOf="parent"/>
  36. <Button
  37. android:id="@+id/to_flutter"
  38. android:layout_width="wrap_content"
  39. android:layout_height="wrap_content"
  40. android:layout_marginTop="20dp"
  41. android:text="前往 Flutter Home"
  42. android:textSize="20sp"
  43. android:textAllCaps="false"
  44. app:layout_constraintLeft_toLeftOf="parent"
  45. app:layout_constraintTop_toBottomOf="@id/result_v"
  46. app:layout_constraintRight_toRightOf="parent" />
  47. <Button
  48. android:id="@+id/to_flutter_fragment"
  49. android:layout_width="wrap_content"
  50. android:layout_height="wrap_content"
  51. android:layout_marginTop="20dp"
  52. android:text="前往 Flutter Fragment"
  53. android:textSize="20sp"
  54. android:textAllCaps="false"
  55. app:layout_constraintLeft_toLeftOf="parent"
  56. app:layout_constraintTop_toBottomOf="@id/to_flutter"
  57. app:layout_constraintRight_toRightOf="parent" />
  58. </androidx.constraintlayout.widget.ConstraintLayout>
  59. </layout>

AndroidManifest.xml

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android">
  2. <application
  3. android:name="${applicationName}"
  4. android:icon="@mipmap/ic_launcher"
  5. android:label="flutter_nav_android"
  6. android:theme="@style/AppTheme">
  7. <activity
  8. android:name="io.flutter.embedding.android.FlutterActivity"
  9. android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
  10. android:hardwareAccelerated="true"
  11. android:windowSoftInputMode="adjustResize" />
  12. <activity android:name=".ui.activity.SchoolActivity" android:exported="true"/>
  13. <activity android:name=".ui.activity.PersonalActivity" android:exported="true"/>
  14. <activity
  15. android:name=".ui.activity.MainActivity"
  16. android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
  17. android:exported="true"
  18. android:hardwareAccelerated="true"
  19. android:launchMode="singleTop"
  20. android:windowSoftInputMode="adjustResize">
  21. <!-- Specifies an Android theme to apply to this Activity as soon as
  22. the Android process has started. This theme is visible to the user
  23. while the Flutter UI initializes. After that, this theme continues
  24. to determine the Window background behind the Flutter UI. -->
  25. <meta-data
  26. android:name="io.flutter.embedding.android.NormalTheme"
  27. android:resource="@style/NormalTheme" />
  28. <intent-filter>
  29. <action android:name="android.intent.action.MAIN" />
  30. <category android:name="android.intent.category.LAUNCHER" />
  31. </intent-filter>
  32. </activity>
  33. <!-- Don't delete the meta-data below.
  34. This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
  35. <meta-data
  36. android:name="flutterEmbedding"
  37. android:value="2" />
  38. </application>
  39. <!-- Required to query activities that can process text, see:
  40. https://developer.android.com/training/package-visibility?hl=en and
  41. https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
  42. In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
  43. <queries>
  44. <intent>
  45. <action android:name="android.intent.action.PROCESS_TEXT" />
  46. <data android:mimeType="text/plain" />
  47. </intent>
  48. </queries>
  49. </manifest>

Flutter代码

book.dart

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. class Book extends StatefulWidget {
  4. const Book({super.key});
  5. @override
  6. State<Book> createState() => _BookState();
  7. }
  8. class _BookState extends State<Book> {
  9. String title = '';
  10. static const String METHOD_CHANNEL_BOOK = 'com.example.flutter_nav_android/book/method';
  11. static const String NAV_FLUTTER_BOOK_NOTICE = 'navFlutterBookNotice';
  12. @override
  13. void initState() {
  14. super.initState();
  15. MethodChannel bookMethodChannel = const MethodChannel(METHOD_CHANNEL_BOOK);
  16. bookMethodChannel.setMethodCallHandler(methodHandler);
  17. }
  18. /// 监听来自 Android端 的消息通道
  19. /// Android端调用了函数,这个handler函数就会被触发
  20. Future<dynamic> methodHandler(MethodCall call) async {
  21. final String methodName = call.method;
  22. switch (methodName) {
  23. case NAV_FLUTTER_BOOK_NOTICE: // 进入当前页面
  24. {
  25. title = call.arguments['title'];
  26. setState(() {});
  27. return 0;
  28. }
  29. default:
  30. {
  31. return PlatformException(
  32. code: '-1',
  33. message: '未找到Flutter端具体实现函数',
  34. details: '具体描述'); // 返回给Android端
  35. }
  36. }
  37. }
  38. @override
  39. Widget build(BuildContext context) {
  40. return Scaffold(
  41. backgroundColor: Colors.amberAccent,
  42. body: Container(
  43. width: MediaQuery.of(context).size.width,
  44. height: MediaQuery.of(context).size.height,
  45. alignment: Alignment.center,
  46. child: Text(
  47. 'Flutter $title',
  48. style: const TextStyle(
  49. fontWeight: FontWeight.bold,
  50. color: Colors.red,
  51. fontSize: 20,
  52. ),
  53. ),
  54. ),
  55. );
  56. }
  57. }

home.dart

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. class Home extends StatefulWidget {
  4. const Home({super.key});
  5. @override
  6. State<Home> createState() => _HomeState();
  7. }
  8. class _HomeState extends State<Home> {
  9. late MethodChannel homeMethodChannel;
  10. String name = '';
  11. String age = '';
  12. static const String METHOD_CHANNEL_HOME = 'com.example.flutter_nav_android/home/method';
  13. static const String NAV_ANDROID_PERSONAL_NOTICE = 'navAndroidPersonalNotice';
  14. static const String NAV_FLUTTER_HOME_NOTICE = 'navFlutterHomeNotice';
  15. static const String POP_NOTICE = 'popNotice';
  16. static const String PERSONAL_POP_NOTICE = 'personalPopNotice';
  17. @override
  18. void initState() {
  19. super.initState();
  20. homeMethodChannel = const MethodChannel(METHOD_CHANNEL_HOME);
  21. homeMethodChannel.setMethodCallHandler(methodHandler);
  22. }
  23. /// 监听来自 Android端 的消息通道
  24. /// Android端调用了函数,这个handler函数就会被触发
  25. Future<dynamic> methodHandler(MethodCall call) async {
  26. final String methodName = call.method;
  27. switch (methodName) {
  28. case NAV_FLUTTER_HOME_NOTICE: // 进入当前页面
  29. {
  30. name = call.arguments['name'];
  31. setState(() {});
  32. return 0;
  33. }
  34. case PERSONAL_POP_NOTICE: // Android Personal 页面 销毁了
  35. {
  36. age = '${call.arguments['age']}';
  37. setState(() {});
  38. return 0;
  39. }
  40. default:
  41. {
  42. return PlatformException(
  43. code: '-1',
  44. message: '未找到Flutter端具体实现函数',
  45. details: '具体描述'); // 返回给Android端
  46. }
  47. }
  48. }
  49. /// 销毁当前页面
  50. popPage() {
  51. if (Navigator.canPop(context)) { // 检查Flutter路由栈中,是否还有其他路由
  52. Navigator.pop(context);
  53. } else {
  54. Map<String, int> map = {'age': 12};
  55. homeMethodChannel.invokeMethod(POP_NOTICE, map);
  56. }
  57. }
  58. /// 前往 Android Personal 页面
  59. navAndroidPersonal() {
  60. Map<String, String> map = {'name': '李四'};
  61. homeMethodChannel.invokeMethod(NAV_ANDROID_PERSONAL_NOTICE, map);
  62. }
  63. @override
  64. Widget build(BuildContext context) {
  65. return Scaffold(
  66. appBar: AppBar(
  67. backgroundColor: Colors.blue,
  68. title: const Text(
  69. 'Flutter Home',
  70. style: TextStyle(
  71. fontWeight: FontWeight.w500,
  72. fontSize: 26,
  73. color: Colors.yellow),
  74. )),
  75. body: SizedBox(
  76. width: MediaQuery.of(context).size.width,
  77. height: MediaQuery.of(context).size.height,
  78. child: Column(
  79. mainAxisAlignment: MainAxisAlignment.center,
  80. crossAxisAlignment: CrossAxisAlignment.center,
  81. children: [
  82. Padding(
  83. padding: const EdgeInsets.only(bottom: 16),
  84. child: RichText(
  85. text: TextSpan(
  86. text: '接收初始化参数:',
  87. style: const TextStyle(color: Colors.black, fontSize: 20),
  88. children: [
  89. TextSpan(
  90. text: name,
  91. style: const TextStyle(color: Colors.red,fontWeight: FontWeight.bold),
  92. )
  93. ])),
  94. ),
  95. Padding(
  96. padding: const EdgeInsets.only(bottom: 16),
  97. child: RichText(
  98. text: TextSpan(
  99. text: '接收上一页返回参数:',
  100. style: const TextStyle(color: Colors.black, fontSize: 20),
  101. children: [
  102. TextSpan(
  103. text: age,
  104. style: const TextStyle(color: Colors.red,fontWeight: FontWeight.bold),
  105. )
  106. ])),
  107. ),
  108. Padding(
  109. padding: const EdgeInsets.only(bottom: 8),
  110. child: ElevatedButton(
  111. onPressed: navAndroidPersonal,
  112. child: const Text(
  113. '前往 Android Personal',
  114. style: TextStyle(fontSize: 20),
  115. ),
  116. ),
  117. ),
  118. ElevatedButton(
  119. onPressed: popPage,
  120. child: const Text(
  121. '返回 上一页',
  122. style: TextStyle(fontSize: 20),
  123. ),
  124. ),
  125. ],
  126. ),
  127. ),
  128. );
  129. }
  130. }

login.dart

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. class Login extends StatefulWidget {
  4. const Login({super.key});
  5. @override
  6. State<Login> createState() => _LoginState();
  7. }
  8. class _LoginState extends State<Login> {
  9. late MethodChannel loginMethodChannel;
  10. String name = '';
  11. final String METHOD_CHANNEL_LOGIN = 'com.example.flutter_nav_android/login/method';
  12. static const String NAV_FLUTTER_LOGIN_NOTICE = 'navFlutterLoginNotice';
  13. final String POP_NOTICE = 'popNotice';
  14. @override
  15. void initState() {
  16. super.initState();
  17. loginMethodChannel = MethodChannel(METHOD_CHANNEL_LOGIN);
  18. loginMethodChannel.setMethodCallHandler(methodHandler);
  19. }
  20. /// 监听来自 Android端 的消息通道
  21. /// Android端调用了函数,这个handler函数就会被触发
  22. Future<dynamic> methodHandler(MethodCall call) async {
  23. final String methodName = call.method;
  24. switch (methodName) {
  25. case NAV_FLUTTER_LOGIN_NOTICE: // 进入当前页面
  26. {
  27. name = call.arguments['name'];
  28. setState(() {});
  29. return 0;
  30. }
  31. default:
  32. {
  33. return PlatformException(code: '-1', message: '未找到Flutter端具体实现函数', details: '具体描述'); // 返回给Android端
  34. }
  35. }
  36. }
  37. /// 销毁当前页面
  38. popPage() {
  39. if (Navigator.canPop(context)) { // 检查Flutter路由栈中,是否还有其他路由
  40. Navigator.pop(context);
  41. } else {
  42. Map<String, int> map = {'age': 28};
  43. loginMethodChannel.invokeMethod(POP_NOTICE, map);
  44. }
  45. }
  46. @override
  47. Widget build(BuildContext context) {
  48. return Scaffold(
  49. appBar: AppBar(
  50. backgroundColor: Colors.blue,
  51. title: const Text(
  52. 'Flutter Login',
  53. style: TextStyle(
  54. fontWeight: FontWeight.w500,
  55. fontSize: 26,
  56. color: Colors.yellow),
  57. )),
  58. body: SizedBox(
  59. width: MediaQuery.of(context).size.width,
  60. height: MediaQuery.of(context).size.height,
  61. child: Column(
  62. mainAxisAlignment: MainAxisAlignment.center,
  63. crossAxisAlignment: CrossAxisAlignment.center,
  64. children: [
  65. Padding(
  66. padding: const EdgeInsets.only(bottom: 16),
  67. child: RichText(
  68. text: TextSpan(
  69. text: '接收初始化参数:',
  70. style: const TextStyle(color: Colors.black, fontSize: 20),
  71. children: [
  72. TextSpan(
  73. text: name,
  74. style: const TextStyle(color: Colors.red,fontWeight: FontWeight.bold),
  75. )
  76. ])),
  77. ),
  78. ElevatedButton(
  79. onPressed: popPage,
  80. child: const Text(
  81. '返回 上一页',
  82. style: TextStyle(fontSize: 20),
  83. ),
  84. ),
  85. ],
  86. ),
  87. ),
  88. );
  89. }
  90. }

student.dart

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. class Student extends StatefulWidget {
  4. const Student({super.key});
  5. @override
  6. State<Student> createState() => _StudentState();
  7. }
  8. class _StudentState extends State<Student> {
  9. String title = '';
  10. static const String METHOD_CHANNEL_STUDENT = 'com.example.flutter_nav_android/student/method';
  11. static const String NAV_FLUTTER_STUDENT_NOTICE = 'navFlutterStudentNotice';
  12. @override
  13. void initState() {
  14. super.initState();
  15. MethodChannel bookMethodChannel = const MethodChannel(METHOD_CHANNEL_STUDENT);
  16. bookMethodChannel.setMethodCallHandler(methodHandler);
  17. }
  18. /// 监听来自 Android端 的消息通道
  19. /// Android端调用了函数,这个handler函数就会被触发
  20. Future<dynamic> methodHandler(MethodCall call) async {
  21. final String methodName = call.method;
  22. switch (methodName) {
  23. case NAV_FLUTTER_STUDENT_NOTICE: // 进入当前页面
  24. {
  25. title = call.arguments['title'];
  26. setState(() {});
  27. return 0;
  28. }
  29. default:
  30. {
  31. return PlatformException(
  32. code: '-1',
  33. message: '未找到Flutter端具体实现函数',
  34. details: '具体描述'); // 返回给Android端
  35. }
  36. }
  37. }
  38. @override
  39. Widget build(BuildContext context) {
  40. return Scaffold(
  41. backgroundColor: Colors.cyan,
  42. body: Container(
  43. width: MediaQuery.of(context).size.width,
  44. height: MediaQuery.of(context).size.height,
  45. alignment: Alignment.center,
  46. child: Text(
  47. 'Flutter $title',
  48. style: const TextStyle(
  49. fontWeight: FontWeight.bold,
  50. color: Colors.white,
  51. fontSize: 20,
  52. ),
  53. ),
  54. ),
  55. );
  56. }
  57. }

main.dart

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_nav_android/book.dart';
  3. import 'package:flutter_nav_android/student.dart';
  4. import 'home.dart';
  5. import 'login.dart';
  6. void main() {
  7. runApp(const MyApp());
  8. }
  9. class MyApp extends StatelessWidget {
  10. const MyApp({super.key});
  11. @override
  12. Widget build(BuildContext context) {
  13. return MaterialApp(
  14. title: 'Flutter Demo',
  15. debugShowCheckedModeBanner: false,
  16. theme: ThemeData(
  17. colorScheme: ColorScheme.fromSeed(
  18. seedColor: Colors.deepPurple,
  19. ),
  20. useMaterial3: true,
  21. ),
  22. routes: {
  23. '/home': (context) => const Home(),
  24. '/login': (context) => const Login(),
  25. '/book': (context) => const Book(),
  26. '/student': (context) => const Student(),
  27. },
  28. initialRoute: '/home',
  29. );
  30. }
  31. }

踩坑

  • 一个路由坑,Flutter 加载 根命名路由标识,默认是 " / ",如果你在Flutter端使用了 " / " 作为根路由页面,有时候,从Android 跳转 Flutter页面时,它会将 根路由页面 先push进栈,再push你的目标页面进栈,会多出一个页面
  • 所有我直接不用 " / " 标识,而使用页面对应的路由标识字符串,来指定根路由。
  1. // 原来带坑的写法
  2. // routes: {
  3. // '/': (context) => const Home(),
  4. // '/login': (context) => const Login(),
  5. // '/personal': (context) => const Personal()
  6. // },
  7. // initialRoute: '/',
  8. // 解决方式的写法
  9. routes: {
  10. '/home': (context) => const Home(),
  11. '/login': (context) => const Login(),
  12. '/personal': (context) => const Personal()
  13. },
  14. initialRoute: '/home',

奇技淫巧

在案例中,我使用的是 命名路由Channel方式 进行 页面跳转、传参,下面直接使用引擎进行 页面跳转、传参,但实用价值不高,因为弊端太大;

比如:

  • 只提供了List<String>类型,进行传参;
  • 目标Flutter页面内的widget,默认参数会全部失效;
  • Flutter的Widget默认参数,是由主文件内的 MaterialApp 组件提供的,一个Flutter应用,一般只会使用一个 MaterialApp,它代表返回一个App,如果将目标Flutter页面套上 MaterialApp ,可以解决这个默认参数问题,但会引发 路由问题
  • 不过也有适用场景:让每个Flutter页面完全独立,之间没有任何交互,比如跳转、数据共享等等,这样路由就不需要了,让每个Flutter页面都使用 MaterialApp,当作App和原生交互;

综上所述,大家将这种方式当作扩展知识就好了。

Android代码

  1. class MainActivity : AppCompatActivity(), View.OnClickListener {
  2. ... ...
  3. override fun onCreate(savedInstanceState: android.os.Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. ... ...
  6. val flutterEngine = FlutterEngine(this)
  7. // 定义参数
  8. val dartEntrypointArgs = mutableListOf<String>()
  9. dartEntrypointArgs.add("张三")
  10. // 这种方式传参数,会导致这个Flutter页面中的Widget默认参数,全部失效,
  11. // 这种只有 Dart主入口文件,比如main.dart的 main函数才能接收到参数
  12. // void main(List<String args>) {}
  13. // flutterEngine.dartExecutor.executeDartEntrypoint(
  14. // DartExecutor.DartEntrypoint.createDefault(),
  15. // dartEntrypointArgs
  16. // )
  17. // 这种可以指定页面接收,但需要在主入口文件里先声明
  18. // void showPersonal(List<String> args) {}
  19. flutterEngine.dartExecutor.executeDartEntrypoint(
  20. DartExecutor.DartEntrypoint(
  21. FlutterInjector.instance().flutterLoader().findAppBundlePath(),
  22. "showPersonal"), // 找到目标Flutter页面提供的 暴露函数
  23. dartEntrypointArgs)
  24. FlutterEngineCache.getInstance().put("personal_engine", flutterEngine)
  25. }
  26. override fun onClick(v: View?) {
  27. ... ...
  28. val map: MutableMap<String, String> = mutableMapOf<String, String>()
  29. map["name"] = "张三"
  30. startActivity(
  31. FlutterActivity
  32. .withCachedEngine("personal_engine") // 获取缓存好的引擎
  33. .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent) // 背景改为透明,不然切换页面时,会闪烁黑色
  34. .build(this))
  35. }
  36. }

Flutter代码

main.dart(主文件)

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_nav_android/personal.dart';
  3. void main(List<String> args) {
  4. debugPrint('args:$args');
  5. runApp(const MyApp());
  6. }
  7. /// 注解说明文档:https://mrale.ph/dartvm/compiler/aot/entry_point_pragma.html
  8. /// 注解:表明它可以在 AOT 模式下直接从本机或 VM 代码解析、分配或调用
  9. @pragma("vm:entry-point")
  10. void showPersonal(List<String> args) { // 在主文件入口暴露出来
  11. debugPrint('args:$args');
  12. runApp(Personal(title: args.first));
  13. }
  14. class MyApp extends StatelessWidget {
  15. const MyApp({super.key});
  16. @override
  17. Widget build(BuildContext context) {
  18. return MaterialApp(
  19. title: 'Flutter Demo',
  20. debugShowCheckedModeBanner: false,
  21. theme: ThemeData(
  22. colorScheme: ColorScheme.fromSeed(
  23. seedColor: Colors.deepPurple,
  24. ),
  25. useMaterial3: true,
  26. ),
  27. );
  28. }
  29. }

personal.dart(目标页面)

  1. import 'package:flutter/material.dart';
  2. class Personal extends StatefulWidget {
  3. final String? title;
  4. const Personal({super.key,this.title});
  5. @override
  6. State<Personal> createState() => _PersonalState();
  7. }
  8. class _PersonalState extends State<Personal> {
  9. /// 在这个页面中,使用的Widget 默认参数全部失效,外层套上 Material组件 也无效
  10. @override
  11. Widget build(BuildContext context) {
  12. return Container(
  13. color: Colors.white,
  14. width: MediaQuery.of(context).size.width,
  15. height: MediaQuery.of(context).size.height,
  16. alignment: Alignment.center,
  17. child: Directionality(
  18. textDirection: TextDirection.ltr,
  19. child: Text(
  20. widget.title ?? '',
  21. style: const TextStyle(
  22. color: Colors.lightBlue,
  23. fontSize: 30,
  24. ),
  25. )),
  26. );
  27. }
  28. }

FlutterEngineGroup

  • 如果你接受以上缺点,可以使用 FlutterEngineGroup,这个东西就是换成了单例写法,我们自己写单例,需要处理一个问题,比如这个需求:同时获取两个Flutter引擎,这里就要通过判空新建一个Flutter引擎;
  • 而 FlutterEngineGroup 已经处理了这个问题,自首个Flutter引擎起,后面多出的Flutter引擎,都是其子类,如果只剩下最后一个,那么这个Flutter引擎将和首个Flutter引擎性能特征相同;
  • FlutterEngineGroup官方文档:多个 Flutter 页面或视图 - Flutter 中文文档 - Flutter 中文开发者网站 - Flutter
  • 我个人体验上来说,不使用单例,性能也足够了,如果有很多混合的Flutter页面,那当我没说
    声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/669942
推荐阅读
相关标签