iOS & Android 接入 Flutter
一、引言
使用 flutter 从零开始开发 App 是一件轻松惬意的事情,但对于一些成熟的产品来说,完全摒弃原有 App 的历史沉淀,全面转向 Flutter 是不现实的。因此使用 Flutter 去统一 Android、iOS 技术栈,把它作为已有原生App 的扩展能力,通过有序推进来提升移动终端的开发效率。 目前,想要在已有的原生 App 里嵌入一些 Flutter 页面主要有两种方案。一种是将原生工程作为 Flutter 工程的子工程,由 Flutter 进行统一管理,这种模式称为统一管理模式。另一种是将 Flutter 工程作为原生工程的子模块,维持原有的原生工程管理方式不变,这种模式被称为三端分离模式,三端模式如下图;
image.png二、各端集成方式:
首先需要确保当前 Flutter 项目是 module 工程,假设我们的项目路径为 some/path/my_flutter;
(一)iOS 接入 Flutter
方案 A:
- 在 Flutter 项目根目录下执行打包操作:
cd some/path/my_flutter
flutter build ios-framework --output=../flutter_framework
Building with sound null safety
Building frameworks for com.example.wallpaper in debug mode...
├─Copying Flutter.xcframework... 392ms
├─Building App.xcframework... 38.2s
├─Building plugins... 63.7s
└─Moving to flutter_framework/Debug 375ms
Building frameworks for com.example.wallpaper in profile mode...
├─Copying Flutter.xcframework... 416ms
├─Building App.xcframework... 81.8s
├─Building plugins... 71.1s
└─Moving to flutter_framework/Profile 335ms
Building frameworks for com.example.wallpaper in release mode...
├─Copying Flutter.xcframework... 1,728ms
├─Building App.xcframework... 94.3s
├─Building plugins... 65.8s
└─Moving to flutter_framework/Release 317ms
Frameworks written to some/path/my_flutter/flutter_framework.
2.打包完成后,所有 framework 文件会保存到 flutter_framework 文件夹,文件目录如下:
some/path/my_flutter/
└── flutter_framework/
├── Debug/
│ ├── Flutter.xcframework
│ ├── App.xcframework
│ ├── FlutterPluginRegistrant.xcframework (only if you have plugins with iOS platform code)
│ └── example_plugin.xcframework (each plugin is a separate framework)
├── Profile/
│ ├── Flutter.xcframework
│ ├── App.xcframework
│ ├── FlutterPluginRegistrant.xcframework
│ └── example_plugin.xcframework
└── Release/
├── Flutter.xcframework
├── App.xcframework
├── FlutterPluginRegistrant.xcframework
└── example_plugin.xcframework
3. 可以直接将编译产物中的所有 framework 拖到项目中就可以使用了,这边就不赘述了,这里主要讲解远端 pod 依赖的模式;
其实只有 Release 的 framework 是需要上传到远程的,所以我们将 Release 文件夹下的所有文件上传到专门存储 framework 的 gitlab 仓库里;
4.在 spec 仓库中创建一个 Flutter-wallpaper.podspec 文件,并放到相对应的版本文件夹下,文件内容如下:
Pod::Spec.new do |s|
s.name = 'Flutter-wallpaper'
s.version = '1.0.11'
s.summary = 'flutter 壁纸组件'
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://xxx/xxx/ios_sdk/iOS_frameworks'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'xxx@xxx.com' => 'xxx@xxx.com' }
s.source = { :git => 'git@xxx/xxx/ios_sdk/iOS_frameworks.git'}
s.ios.deployment_target = '9.0'
s.ios.vendored_frameworks = 'flutter-lib/wallpaper/1.0.11/App.xcframework',
'flutter-lib/wallpaper/1.0.11/FMDB.xcframework',
'flutter-lib/wallpaper/1.0.11/Flutter.xcframework',
'flutter-lib/wallpaper/1.0.11/FlutterPluginRegistrant.xcframework',
'flutter-lib/wallpaper/1.0.11/Reachability.xcframework',
'flutter-lib/wallpaper/1.0.11/Toast.xcframework',
'flutter-lib/wallpaper/1.0.11/connectivity.xcframework',
'flutter-lib/wallpaper/1.0.11/device_info.xcframework',
'flutter-lib/wallpaper/1.0.11/fluttertoast.xcframework',
'flutter-lib/wallpaper/1.0.11/image_gallery_saver.xcframework',
'flutter-lib/wallpaper/1.0.11/package_info_plus.xcframework',
'flutter-lib/wallpaper/1.0.11/path_provider.xcframework',
'flutter-lib/wallpaper/1.0.11/sqflite.xcframework',
'flutter-lib/wallpaper/1.0.11/vibration.xcframework'
end
5.上面步骤都完成后,我们就可以通过 pod 来引用 flutter 模块了,在 Podfile 文件里面添加上 flutter 模块的版本描述:
pod 'Flutter-wallpaper', '1.0.11'
6.展示 FlutterViewController :
FlutterEngine *flutterEngine = [[FlutterEngine alloc] initWithName:@"io.flutter" project:nil];
[flutterEngine runWithEntrypoint:nil];
// 该方法要放到 runWithEntrypoint 之后
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil];
[self.navigationController pushViewController:flutterViewController animated:YES]
(二)android 接入 Flutter
集成方案:
方案 A (Google推荐的打包AAR方式):
- 在 flutter 项目根目录下执行打包操作:
<pre>cd some/path/my_flutter
flutter build aar
2.打包完成后,命令行会输出如下集成步骤,帮助集成 flutter 模块;
Building without sound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety
Running Gradle task 'assembleAarDebug'...
Running Gradle task 'assembleAarDebug'... Done 42.3s
✓ Built build/host/outputs/repo.
Running Gradle task 'assembleAarProfile'...
Running Gradle task 'assembleAarProfile'... Done 70.8s
✓ Built build/host/outputs/repo.
Running Gradle task 'assembleAarRelease'...
Running Gradle task 'assembleAarRelease'... Done 82.0s
✓ Built build/host/outputs/repo.
Consuming the Module
1\. Open <host>/app/build.gradle
2\. Ensure you have the repositories configured, otherwise add them:
String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"
repositories {
maven {
url '/Users/yoser/Desktop/work/Business/wallpaper/build/host/outputs/repo'
}
maven {
url "$storageUrl/download.flutter.io"
}
}
3\. Make the host app depend on the Flutter module:
dependencies {
debugImplementation 'com.example.wallpaper:flutter_debug:1.0'
profileImplementation 'com.example.wallpaper:flutter_profile:1.0'
releaseImplementation 'com.example.wallpaper:flutter_release:1.0'
}
4\. Add the `profile` build type:
android {
buildTypes {
profile {
initWith debug
}
}
}
To learn more, visit https://flutter.dev/go/build-aar
主要分为三个步骤:
(1)在 app/build.gradle 文件中添加仓库索引;
(2)在 app/build.gradle 文件中添加库依赖;
(3)通过 profile 来控制打包所使用的依赖包;
打包完成后的文件目录如下,其实就是一个本地的 maven 仓库,可以将该仓库发布到远程服务器上引入,下面为了方便,我采用的是本地仓库的方式;
build/host/outputs/repo
└── com
└── example
└── my_flutter
├── flutter_release
│ ├── 1.0
│ │ ├── flutter_release-1.0.aar
│ │ ├── flutter_release-1.0.aar.md5
│ │ ├── flutter_release-1.0.aar.sha1
│ │ ├── flutter_release-1.0.pom
│ │ ├── flutter_release-1.0.pom.md5
│ │ └── flutter_release-1.0.pom.sha1
│ ├── maven-metadata.xml
│ ├── maven-metadata.xml.md5
│ └── maven-metadata.xml.sha1
├── flutter_profile
│ ├── ...
└── flutter_debug
└── ...
3.由于我使用的是最新的项目,所以仓库路径配置放在 settings.gradle 中设置:
String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
// s repository is going to shut down soon
// 本地仓库路径
maven {
url '/Users/yoser/Desktop/work/Business/wallpaper/build/host/outputs/repo'
}
// flutter.so 和 flutter_embedding.jar 所在的远端仓库
maven {
url "$storageUrl/download.flutter.io"
}
}
}
rootProject.name = "FlutterDemo"
include ':app'
4.然后在 app/build.gradle 中添加 Flutter 库依赖;
dependencies {
implementation 'com.example.wallpaper:flutter_debug:1.0'
}
因为用的是模拟器,而且没有配置 profile 去控制引用的包类型,所以直接用 debug 来运行代码,因为只有 debug 的库有包含 x86 架构,到这一步,flutter 已经集成到项目中;
展示页面
(1)添加 FlutterActivity 到 AndroidManifest.xml 中:
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
/>
(2)普通跳转 FlutterActivity:
myButton.setOnClickListener {
startActivity(
FlutterActivity.createDefaultIntent(this)
)
}
(3)设置路由的方式跳转:
myButton.setOnClickListener {
startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("/my_route")
.build(this)
)
}
(4)缓存 Flutter 引擎方式跳转:
class MyApplication : Application() {
lateinit var flutterEngine : FlutterEngine
override fun onCreate() {
super.onCreate()
// Instantiate a FlutterEngine.
flutterEngine = FlutterEngine(this)
// Configure an initial route.
flutterEngine.navigationChannel.setInitialRoute("your/route/here");
// Start executing Dart code to pre-warm the FlutterEngine.
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
// Cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine)
}
}
myButton.setOnClickListener {
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.build(this)
)
}
参考: