android原生项目集成flutter模块
-
创建flutter模块
使用android studio,File->New->New Flutter Project...->Flutter Module->Next->Next->Finish,即可完成,期间可以修改包名、项目名称等。
-
配置settings.gradle
setBinding(new Binding(gradle: this)) evaluate(new File(settingsDir.parent, "fluttermodule/.android/include_flutter.groovy")) //fluttermodule是flutter模块项目名称
-
配置build.gradle
//flutter是默认模块名称,具体看build/outputs/aar下的aar包名称,可以通过settings.gradle里的include(':test')和 project(':test').projectDir = new File('项目路径')修改名称为test并指定项目路径 api project(path: ':flutter')
-
代码
//BaseActivity必须继承AppCompatActivity,才有ActivityLifeCycle。 class FlutterTestActivity : BaseActivity() { override fun setLayout() = R.layout.m_activity_flutter_test private val flutterEngineId = "flutterEngineId" private var engine: FlutterEngine? = null override fun initView(view: View) { setToolbarTitle("flutter测试页面") engine = FlutterEngineCache.getInstance().get(flutterEngineId) if (engine == null) { engine = FlutterEngine(this) engine?.dartExecutor?.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) FlutterEngineCache.getInstance().put(flutterEngineId, engine) } val view = createFlutterView() view.attachToFlutterEngine(engine!!) } private fun createFlutterView(): FlutterView { val flutterView = FlutterView(this) //默认加载flutter侧的main.dart文件 val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) binding.flContain.addView(flutterView, params) return flutterView } override fun initEvent() { } override fun createPresenter() = FlutterTestPresenter() override fun onResume() { super.onResume() engine?.lifecycleChannel?.appIsResumed() } override fun onPause() { super.onPause() engine?.lifecycleChannel?.appIsInactive() } override fun onStop() { super.onStop() engine?.lifecycleChannel?.appIsPaused() } }