我是靠谱客的博主 潇洒电脑,这篇文章主要介绍有赞基于Flutter的移动端跨平台App架构实践,现在分享给大家,希望可以做个参考。

来源 | 有赞Coder(ID:youzan_coder)

文 | 张玉柱 on 电商移动

一、背景

目前准备试水 Flutter,但是多数 native 开发是不了解 Flutter,因此需要设计一种比较“舒服”的集成方式。


二、混编方案

2.1 方案考量

  • 如果直接采用 Flutter 工程结构来作为日常开发,那这部分 Native 开发也需要配置Flutter环境, 相当程度的了解 Flutter 一些技术,成本比较大;

  • 同时如果工程耦合,对于开发过程也是很难受的。

基于以上两点思考,针对 Android iOS 有如下方案:

2.2 Android

先看下官方的集成方式:

复制代码
1
2
3
4
5
# setting.gradle setBinding(new Binding([gradle: this])) evaluate(new File( '../managementcenter/.android/include_flutter.groovy' ))
复制代码
1
2
3
4
5
# build.gradle dependencies { implementation project(':flutter') ........... }

这种方式使得工程强耦合,虽然便于开发调试,但是违背了第一点,大多数 native 同学都需要配置 Flutter 环境, 成本很大。

2.3 iOS

2.3.1 官方 iOS 混编方案简介

  • 在native项目 Podfile中通过 eval binding特性注入 podhelper.rb脚本,在 pod install/update 时执行此脚本,脚本主要处理:

  • Pod本地依赖Flutter引擎(Flutter.framework) 与Flutter插件注册表(FlutterPluginRegistrant)

  • Flutter插件通过 flutter packagesget指令安装后生成的 .flutter-plugins文件解析,然后Pod本地依赖所有的插件

  • 在pod install执行完的钩子 post_install中,获取当前pod target工程对象,导入 Generated.xcconfig配置,其中都为环境变量的配置,主要为后续的 xcode_backend.sh脚本执行做准备

  • 在构建阶段 BuildPhases中注入构建是需要执行的 xcode_backend.sh脚本,脚本主要完成Flutter产物的构建并将其添加到对应的native工程中去,后续会进一步介绍此脚本

2.3.2 优点

  • 无缝开发,配置好后就可以只在 Flutter 工程内进行业务开发,无缝同步到 native 工程中

  • 不需要单独拆分组件,免去管理组件的版本及发布成本

2.3.3 缺点

  • 非常耦合,需要修改原有 native 工程配置,需要添加特定脚本去编译 Flutter

  • 需要修改原有 pod 的 xcconfig 配置

  • 所有团队开发成员都必须要配置 Flutter 开发环境才能编译成功

2.4 小结

基于以上思考,同时考虑到某个 Flutter 业务模块可能会引入到不同的 App 中,同时考虑到某个业务实现方式方面的解耦(某个业务可能用 native, flutter, weex 开发),有以下方案(中间产物库每个 Flutter 业务模块都是独立的):

Android:

640?wx_fmt=png

iOS:

640?wx_fmt=png


三、Flutter产物结构

3.1 Android

640?wx_fmt=png

3.2 iOS

640?wx_fmt=png

关于编译模式了解更多可参考查看 Flutter 的编译模式。


四、Flutter 产物收集

4.1 Android

在 Android 端集成 Flutter 较为简单,只需要获取到上文所讲的 Flutter 产物即 aar 文件。但是由于插件文件散落每次获取比较麻烦所以目前简单用脚本收集。

脚本收集主要是依靠项目里 .flutter_plugins 文件,该文件会记录 flutter 项目中引用的插件名以及本地路径等,因此可以通过该路径抓取插件的 aar 文件。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from shutil import copyfile import os import requests # 抓取文件类型 BuildRelease = True aarType = "-release.aar" if BuildRelease else "-debug.aar" pluginFilePath = '../.flutter-plugins' # 当前项目的flutter.aar currentFlutterPath = '../.android/Flutter/build/outputs/aar/' # 输出地址 outputFilePath = os.path.abspath('flutter_aar.py').replace("flutter_aar.py", "aars/") endPath = 'android/build/outputs/aar/' def collect_aar(plugins): all_collection_success = True if os.path.exists(outputFilePath): print('copy aar to: ' + outputFilePath) else: print('target path: ' + outputFilePath + ' not exist') os.makedirs(outputFilePath) print('create target path: ' + outputFilePath) for key, value in plugins.items(): aar_path = value + key + aarType try: copyfile(aar_path, outputFilePath + key + aarType) print('copy flutter aar success at path: ' + aar_path) except IOError: all_collection_success = False print('copy flutter aar error at path: ' + aar_path) pass file_object = open(pluginFilePath, 'r') try: plugin_map = {} for line in file_object: array = line.split('=') plugin_map[array[0]] = array[1].replace('n', '') + endPath plugin_map['flutter'] = currentFlutterPath collect_aar(plugin_map) finally: file_object.close()

目前该python脚本只抓取 Release 的 aar 文件,如果需要获取 debug 的可以手动修改:

复制代码
1
BuildRelease = False

执行抓取脚本 ./flutter_aar.sh

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env bash cd .. cd .android echo "start clean" ./gradlew clean echo "start assembleRelease" ./gradlew assembleRelease cd .. cd android-build echo "clean old aar file" rm -rf aars echo "start copy aar file" # 只抓取release python flutter_aar.py echo "copy aar file finish"

脚本执行完 Flutter 产物 aar 文件统一生成在根目录下 android-build 文件夹中。

640?wx_fmt=png

4.2 iOS

通过查看 Flutter 编译脚本 xcode_backend.sh 和测试单独引入编译产物,发现其实 只要拥有Flutter的编译产物,宿主项目就可以接入Flutter的功能。

4.2.1 脚本简单分析

  • engine/Flutter.framework Flutter 核心库拷贝 -> Flutter.framework

复制代码
1
2
3
4
5
6
7
8
9
10
11
if [[ -e "${project_path}/.ios" ]]; then RunCommand rm -rf -- "${derived_dir}/engine" mkdir "${derived_dir}/engine" RunCommand cp -r -- "${flutter_podspec}" "${derived_dir}/engine" RunCommand cp -r -- "${flutter_framework}" "${derived_dir}/engine" RunCommand find "${derived_dir}/engine/Flutter.framework" -type f -exec chmod a-w "{}" ; else RunCommand rm -rf -- "${derived_dir}/Flutter.framework" RunCommand cp -r -- "${flutter_framework}" "${derived_dir}" RunCommand find "${derived_dir}/Flutter.framework" -type f -exec chmod a-w "{}" ; fi

  • debug 模式下 Dart 业务代码编译(JIT) -> App.framework

复制代码
1
2
3
4
5
6
7
RunCommand eval "$(echo "static const int Moo = 88;" | xcrun clang -x c ${arch_flags} -dynamiclib -Xlinker -rpath -Xlinker '@executable_path/Frameworks' -Xlinker -rpath -Xlinker '@loader_path/Frameworks' -install_name '@rpath/App.framework/App' -o "${derived_dir}/App.framework/App" -)"

  • 非 debug 模式下 Dart 业务代码编译(AOT) -> App.framework

复制代码
1
2
3
4
5
6
7
8
9
10
RunCommand "${FLUTTER_ROOT}/bin/flutter" --suppress-analytics ${verbose_flag} build aot --output-dir="${build_dir}/aot" --target-platform=ios --target="${target_path}" --${build_mode} --ios-arch="${archs}" ${local_engine_flag} ${track_widget_creation_flag}

  • 资源文件等打包 -> flutter_assets

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
StreamOutput " ├─Assembling Flutter resources..." RunCommand "${FLUTTER_ROOT}/bin/flutter" --suppress-analytics ${verbose_flag} build bundle --target-platform=ios --target="${target_path}" --${build_mode} --depfile="${build_dir}/snapshot_blob.bin.d" --asset-dir="${derived_dir}/App.framework/flutter_assets" ${precompilation_flag} ${local_engine_flag} ${track_widget_creation_flag}


4.2.2 方案分析

设计

640?wx_fmt=png

  • 插件统一编译成.a库,添加对应头文件

  • App.framework 及 engine/Flutter.framework 添加

  • 目前初期 demo 将上述生成的产物统一放入到私有库当中,然后 native 宿主工程 pod 依赖此库,只需要在使用 Flutter 代码的地方 import 对应的头文件即可正常使用

脚本编写
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
echo "==b清理flutter历史编译===" flutter clean echo "===重新生成plugin索引===" flutter packages get echo "===生成App.framework和flutter_assets===" flutter build ios --debug echo "===获取所有plugin并找到头文件===" while read -r line do if [[ ! "$line" =~ ^// ]]; then array=(${line//=/ }) plugin_name=${array[0]} cd .ios/Pods echo "生成lib${plugin_name}.a..." /usr/bin/env xcrun xcodebuild build -configuration Release ARCHS='arm64 armv7' -target ${plugin_name} BUILD_DIR=../../build/ios -sdk iphoneos -quiet /usr/bin/env xcrun xcodebuild build -configuration Debug ARCHS='x86_64' -target ${plugin_name} BUILD_DIR=../../build/ios -sdk iphonesimulator -quiet echo "合并lib${plugin_name}.a..." lipo -create "../../build/ios/Debug-iphonesimulator/${plugin_name}/lib${plugin_name}.a" "../../build/ios/Release-iphoneos/${plugin_name}/lib${plugin_name}.a" -o "../../product/lib${plugin_name}.a" echo "复制头文件" classes=${array[1]}ios/Classes for header in `find "$classes" -name *.h`; do cp -f $header "../../product/" done else echo "读取文件出错" fi done < .flutter-plugins echo "===生成注册入口的二进制库文件===" for reg_enter_name in "FlutterPluginRegistrant" do echo "生成libFlutterPluginRegistrant.a..." /usr/bin/env xcrun xcodebuild build -configuration Release ARCHS='arm64 armv7' -target FlutterPluginRegistrant BUILD_DIR=../../build/ios -sdk iphoneos /usr/bin/env xcrun xcodebuild build -configuration Debug ARCHS='x86_64' -target FlutterPluginRegistrant BUILD_DIR=../../build/ios -sdk iphonesimulator echo "合并libFlutterPluginRegistrant.a..." lipo -create "../../build/ios/Debug-iphonesimulator/FlutterPluginRegistrant/lib$FlutterPluginRegistrant.a" "../../build/ios/Release-iphoneos/FlutterPluginRegistrant/libFlutterPluginRegistrant.a" -o "../../product/libFlutterPluginRegistrant.a" echo "复制头文件" classes="../Flutter/FlutterPluginRegistrant/Classes" for header in `find "$classes" -name *.h`; do cp -f $header "../../product/" done done
  • 后续规划

  • 脚本优化,添加自动pod库检测及上传

  • App.framework/Flutter.framework 体积太大,放到git仓库不太友好,考虑后续上传到CDN,然后在pod安装的时候预先执行脚本把两个产物拉下来


五、Flutter产物上传

5.1 Android

上面产物搜集完成后,需要上传 maven 仓库,方便集成以及版本控制:

复制代码
1

因此引用链如下:

复制代码
1
  • Android

640?wx_fmt=png

  • iOS

640?wx_fmt=png

六、总结

以上比较全面的描述了有赞的 Flutter 混编方案,目前有赞已经在内部使用的App上使用 Flutter 开发了一些页面作为试点。后续会考虑在线上 App 试点,目前正在进行 Flutter 基础库的搭建,之后会专门有文章分享。

 -End- 


想看更多大厂技术架构分享?关注“技术领导力”公众号

640?wx_fmt=jpeg

想跟文章作者、100位互联网大咖交流学习?

添加助理小姐姐Emma

注明“加群”,稍后她会拉你进社区群

640?wx_fmt=jpeg


往期精彩推文:

  • 36份阿里/腾讯/头条/京东...技术干货汇总

  • 阿里技术专家,一次讲透Java的垃圾回收机制!

  • “ZAO”:AI换脸技术有多可怕?隐私泄露?

  • 阿里员工整天996,究竟能挣多少钱?

  • 阿里架构总监一次讲透中台架构,13页PPT

  • 你还用70后的管理方式,管理99年的员工?

最后

以上就是潇洒电脑最近收集整理的关于有赞基于Flutter的移动端跨平台App架构实践的全部内容,更多相关有赞基于Flutter内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部