為了積極擁抱新技術並優化RN的效能問題,所以決定在新業務需求中引入Flutter技術棧
Flutter混合棧開發大致可以分為一下兩種模式
native工程直接依賴開發
具體接入方式為,先在setting.gradle 中加入如下程式碼:
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir,
'../../Flutter Module工程根目錄/.android/include_flutter.groovy'
))
其次在App的build.gradle 中加入如下程式碼:
implementation project(':flutter')
最後在主工程的build.gradle 中加入如下程式碼即可:
repositories {
buildscript {
maven {
url 'http://download.flutter.io'
}
}
}
allprojects {
repositories {
maven {
url 'http://download.flutter.io'
}
}
}
native工程接入aar
新建Flutter module工程
flutter create -t module xx_module
目錄結構如下
xx_modlue
- .android // Android測試工程
- .ios // iOS測試工程
- lib // Flutter主工程
- main.dart // Flutter入口檔案
- pubspec.yaml // Flutter三方包配置檔案
Flutter中提供了將module打包成aar的命令,生成的aar檔案路徑為 xx_modlue/build/host/outputs/repo
flutter build aar
將生成的aar檔案引入Android開發工程即可完成aar的引用
到目前為止整個aar的引入基本是可以正常開發的,但是存在問題,那就是在每次開發都需要手動的將生成的aar包複製到主工程中進行依賴,不僅操作麻煩而且會出錯,所以講Flutter打包及引入流程變成日常開發常用的模式是最佳實踐
flutter 打包上傳流程分析:
為符合日常開發流程,需要將Flutter打成的aar檔案上傳至maven,因此首要任務就是解決將aar上傳至maven問題
檢視生成的aar目錄下面的pom檔案會發現主工程依賴的第三方aar包也會被下載至xx_modlue/build/host/outputs/repo路徑下,pom檔案如下:
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx.flutter</groupId>
<artifactId>xxx</artifactId>
<version>release-0.0.7</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>io.flutter</groupId>
<artifactId>flutter_embedding_release</artifactId>
<version>1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.flutter</groupId>
<artifactId>armeabi_v7a_release</artifactId>
<version>1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.flutter</groupId>
<artifactId>arm64_v8a_release</artifactId>
<version>1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.flutter</groupId>
<artifactId>x86_64_release</artifactId>
<version>1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
分析pom檔案可知在上傳主工程生成的aar的時候我們還需要將下載下來的第三方aar上傳至maven庫,因此我們得知具體工程化指令碼流程如下:
1、獲取生成的aar路徑
2、上傳第三方依賴的aar檔案
3、更新主工程aar的artifactId
4、上傳主工程aar檔案
具體指令碼如下:
deploy_aar(){
mvn deploy:deploy-file \
-DpomFile="$FILE_PATH/$NAME.pom" \
-DgeneratePom=false \
-Dfile="$FILE_PATH/$NAME.aar" \
-Durl="http://xxx.xxx.xxx:xxx/repository/public/" \
-DrepositoryId="nexus" \
-Dpackaging=aar \
-s="mvn-settings.xml" \
-Dversion="$VERSION"
}
projectDir=`pwd`
# 清除Flutter生成檔案
flutter clean
# 獲取pub包
flutter pub get
# 刪除資料夾
rm -rf `pwd`/build/host/outputs/repo/
# 修改版本號
group="com.xxx.flutter"
type="release"
#type="debug"
#type="profile"
version="${type}-0.0.7"
artifactId="xxx"
echo "替換Flutter/build.gradle 中的group 為${group}"
path=`pwd`/.android/Flutter/build.gradle
sed -i '' '29s/^.*$/group "'${group}'"/' ${path}
echo "替換Flutter/build.gradle 中的version 為${version}"
path=`pwd`/.android/Flutter/build.gradle
sed -i '' '30s/^.*$/version "'${version}'"/' ${path}
# 打包AAR
flutter build aar --no-debug --no-profile
# 找到AAR並上傳
path=`pwd`
# shellcheck disable=SC2006
p=`find ${path}/build/host/outputs/repo -type f -name "*${type}*.aar"`
echo "${p}"
array=(${p//'\n'/})
currentName=""
currentPath=""
currentPom=""
currentDir=""
# shellcheck disable=SC2068
for item in ${array[@]}
do
resFile=`basename ${item}`
echo "${item}"
result=$(echo ${resFile} | grep "flutter_release")
if [[ "$result" == "" ]]
then
lenght=${#item}
sub=${item:0:${lenght}-3}
pom="${sub}pom"
resFileLenght=${#resFile}
subDir=${item:0:${lenght}-${resFileLenght}}
curName=`echo ${resFile} | cut -d "-" -f 2`
curNameLenght=${#curName}
subVersion=${curName:0:${curNameLenght}-4}
nameLenght="${#resFile}"
subName=${resFile:0:${nameLenght}-4}
export FILE_PATH="${subDir}"
export NAME="${subName}"
export VERSION=${subVersion}
deploy_aar
else
nameLenght="${#resFile}"
subName=${resFile:0:${nameLenght}-4}
currentName="${subName}"
currentPath=${item}
currentPath=${item}
lenght=${#item}
sub=${item:0:${lenght}-3}
currentPom="${sub}pom"
resFileLenght=${#resFile}
subDir=${item:0:${lenght}-${resFileLenght}}
currentDir=${subDir}
fi
done
cd "${currentDir}"
echo `pwd`
mv "${currentName}.aar" "${artifactId}-${version}.aar"
mv "${currentName}.pom" "${artifactId}-${version}.pom"
cd ${projectDir}
echo `pwd`
currentName="${artifactId}-${version}"
currentPath="${currentDir}${currentName}.aar"
currentPom="${currentDir}${currentName}.pom"
echo "current name is ${currentName}"
echo "current path is ${currentPath}"
echo "currentPom is ${currentPom}"
echo "替換pom artifactId為${artifactId}"
sed -i '' '6s/^.*$/ <artifactId>'${artifactId}'<\/artifactId> /' ${currentPom}
echo "currentDir is ${currentDir}"
echo "currentVersion is ${version}"
export FILE_PATH="${currentDir}"
export NAME="${currentName}"
export VERSION=${version}
deploy_aar
上傳maven成功後,主工程依賴Flutter程式碼就和新增第三方SDK流程一致了。
選型對比
名稱 | 優點 | 缺點 |
---|---|---|
native工程直接依賴開發 | 接入快 | 工程結構複雜,無法將Flutter開發從native開發流程中剝離 |
native工程接入aar | Flutter開發與native開發流程解耦 | 初期接入流程複雜 |
最終選擇為通過maven方式接入aar方便後續擴充
Flutter 混合棧選型
在完成Flutter混合開發接入流程後,會有混合棧管理問題,在混合方案中解決的主要問題是如何去處理交替出現的Flutter和Native頁面。綜合目前的開源框架,選型為FlutterBoost
flutterBoost Flutter端接入:
FlutterBoost.singleton.registerPageBuilders(<String, PageBuilder>{
testhome: (String pageName, Map<dynamic, dynamic> params, String _) =>
MyHomePage(title: ''),
shoppingcar: (String pageName, Map<dynamic, dynamic> params, String _) {
String platformItemNo = '';
if (params.containsKey("platformItemNo")) {
platformItemNo = params['platformItemNo'];
NativeChat.print(platformItemNo);
}
return ShoppingCar(platformItemNo: platformItemNo);
},
login: (String pageName, Map<dynamic, dynamic> params, String _) =>
LoginPage(),
overlay: (String pageName, Map<dynamic, dynamic> params, String _) =>
OverlayPage(),
});
android端接入:
application 初始化程式碼:
val router =
INativeRouter { context, url, urlParams, requestCode, exts ->
PageRouter.openPageByUrl(context, url, urlParams)
}
val boostLifecycleListener = object : FlutterBoost.BoostLifecycleListener {
override fun onEngineCreated() {
}
override fun onPluginsRegistered() {
}
override fun beforeCreateEngine() {
}
override fun onEngineDestroy() {
}
}
val platform = FlutterBoost.ConfigBuilder(application, router)
.isDebug(BuildConfig.DEBUG)
.whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
.renderMode(FlutterView.RenderMode.texture)
.lifecycleListener(boostLifecycleListener)
.build()
FlutterBoost.instance().init(platform)
路由配置程式碼
// PageRouter 路由跳轉及配置頁面
object PageRouter {
/**
* 路由對映
*/
val pageName: HashMap<String?, String?> =
object : HashMap<String?, String?>() {
init {
put("xxxx://shoppingCar", "shoppingCar")
put("xxxx://login", "login")
put("xxxx://home", "home")
put("xxxx://overlay", "overlay")
}
}
const val SHOPPING_CAR = "xxxx://shoppingCar"
const val LOGIN_PAGE = "xxxx://login"
const val OVERLAY = "xxxx://overlay"
const val BUYER_PRODUCT_DETAIL = "xxxx://buyer/productdetail"
const val TEST_SECOND = "xxxx://testSecond"
@JvmOverloads
fun openPageByUrl(
context: Context,
url: String,
params: Map<*, *>?,
requestCode: Int = 0
): Boolean {
val path = url.split("\\?").toTypedArray()[0]
Log.i("openPageByUrl", path)
return try {
when {
pageName.containsKey(path) -> {
val intent =
BoostFlutterActivity.withNewEngine().url(pageName[path]!!)
.params(params!!)
.backgroundMode(BoostFlutterActivity.BackgroundMode.opaque)
.build(context)
if (context is Activity) {
context.startActivityForResult(intent, requestCode)
} else {
context.startActivity(intent)
}
return true
}
url.startsWith(TEST_SECOND) -> {
context.startActivity(
Intent(
context,
SecondActivity::class.java
)
)
return true
}
else -> false
}
} catch (t: Throwable) {
false
}
}
}
native 跳轉邏輯
// 初始化channel通知
FlutterBoost.instance().channel().addMethodCallHandler { call, result ->
when (call.method) {
"baseUrl" -> {
result.success(ApiConstant.getApiUrl())
}
}
}
// 跳轉程式碼
val params = hashMapOf<String, String>()
params["param"] = param
PageRouter.openPageByUrl(this, PageRouter.SHOPPING_CAR, params)
Flutter 測試環境搭建
在混合開發的工程中被吐槽最多的大概就是測試了吧,和native打包在一起除錯費時費力,對前端開發要求高需要了解native的基本流程
本作品採用《CC 協議》,轉載必須註明作者和本文連結