从0开始模拟Flutter-module嵌入Android原生项目的流程。
环境是:xcode13.1、Android studio Arctic Fox | 2020.3.1 Patch 4、Flutter SDK 2.10.1
1、创建文件夹和文件
根据官网的文档,首先,在桌面创建一个名为native_import_flutter_demo的文件夹,然后在该文件夹内分别创建了android_demo、flutter_module两个文件。关于flutter_module,可以用命令行:
flutter create --template module flutter_module
也可直接用Android studio创建


2、设置ndk
官方是这样说的:
android {
//...
defaultConfig {
ndk {
// Filter for architectures supported by Flutter.
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64'
}
}
}
3、引入 Java 8
官方是这样说的:
查看自己的android_demo中已经是这样,所以不用改
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
4、将 Flutter 库打包成由 AAR
cd到flutter_module目录,执行
$ flutter build aar
也可直接用Android studio工具:

执行成功后如下图:

5、安装提示配置gradle
一开始出现这种错误:
后来又遇到Download fastutil-8.4.0-sources jar一直加载问题。最终,连外网,一直等到右下角Gradle的下载完成为止,运行不报错,完成第一步。
按照文档配置如下:

又有报错,大致意思是:

最后在项目右上角Sync一下。
6、运行Android项目
运行成功不报错,则flutter-module嵌入成功。
7、添加一个Flutter页面
在AndroidManifest.xml 文件中的 application 标签内添加:
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
/>
7、添加一个按钮

8、点击跳转
首先导入:
import io.flutter.embedding.android.FlutterActivity;
添加点击事件:
//缓存设置
// Instantiate a FlutterEngine.
flutterEngine = new FlutterEngine(this);
// Start executing Dart code to pre-warm the FlutterEngine.
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
// Cache the FlutterEngine to be used by FlutterActivity.
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine);
Button button1 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
//常规
//FlutterActivity.createDefaultIntent(MainActivity.this)
//缓存
FlutterActivity
.withCachedEngine("my_engine_id")
.build(MainActivity.this)
);
}
});
9、在flutter_module里执行flutter attach 进行热更新
Demo的github地址:native_import_flutter_demo

网友评论