创建 Flutter Module
启动页加载 Flutter
package com.flutter.androidflutter
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
跳转到 Flutter 页面
package com.flutter.androidflutter
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
startActivity(Intent(this,SecondFlutterActivity::class.java))
}
}
}
package com.flutter.androidflutter
import io.flutter.embedding.android.FlutterActivity
class SecondFlutterActivity:FlutterActivity()
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.flutter.androidflutter">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
...
<activity android:name=".SecondFlutterActivity"/>
</application>
</manifest>
startActivity(Intent(this,FlutterActivity::class.java))
startActivity(FlutterActivity.createDefaultIntent(this))
<activity android:name="io.flutter.embedding.android.FlutterActivity"/>
class OnePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),body: Center(
child: Text('这是 One 页面'),),);
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',theme: ThemeData(
primarySwatch: Colors.blue,routes: {
'one_page':(context){
return OnePage();
},'two_page':(context){
return TwoPage();
}
},home: MyHomePage(title: 'Flutter Demo Home Page'),);
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("one_page")
.build(this)
)
}
}
}
引擎缓存
class MyApplication : Application() {
lateinit var flutterEngine: FlutterEngine
override fun onCreate() {
super.onCreate()
flutterEngine = FlutterEngine(this)
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache
.getInstance()
.put("engine_id",flutterEngine)
}
}
startActivity(
FlutterActivity
.withCachedEngine("engine_id")
.build(this)
)
flutterEngine.destroy()
flutterEngine = FlutterEngine(this)
flutterEngine.navigationChannel.setInitialRoute("one_page")
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache
.getInstance()
.put("engine_id",flutterEngine)