Flutter混合工程工程化编译改造系列:add to app源码分析
add to app
详细教程文档:Add Flutter to existing apps
主要步骤:
- 创建FlutterModule:flutter create -t module xxx
- 在Host App的settings.gradle文件添加如下配置:
1
2
3
4
5
6
7// MyApp/settings.gradle
include ':app' // assumed existing content
setBinding(new Binding([gradle: this])) // new
evaluate(new File( // new
settingsDir.parentFile, // new
'my_flutter/.android/include_flutter.groovy' // new
)) - 依赖flutter module库:
1
2
3dependencies {
implementation project(':flutter')
}
源码分析
通过阅读Flutter官方文档,Flutter的源码分为两部分:
Flutter Framework源码的环境配置与编译都比较容易,主要两步:
- clone代码后,把flutter/bin目录添加到环境变量里,执行任务flutter的命令,都会自动编译flutter tool
- 修改flutter tool源码后,重新编译flutter tool:
1
2
3cd flutter_sdk_path
rm ./bin/cache/flutter_tools.stamp
rm ./bin/cache/flutter_tools.snapshot
flutter create -t module过程分析
flutter create的源码路径:flutter/packages/flutter_tools/lib/src/commands/create.dart
flutter create 命令都是通过template来创建,但create app与create module的模板不一样,create module处于beta阶段:
- 创建的Platform代码在.android文件里
- 执行flutter create, pub命令,会强制删除.android再重建
工程结构分析
新增一个.android/Flutter Module的主要作用:
- 提供一个Flutter类和FlutterFragment类
- 初始化flutter: FlutterMain.startInitialization()
- 创建FlutterView:new FlutterView(activity, null, nativeView)
- 注册Plugin插件
- 通过插flutter的gradle插件,编译整个Flutter工程,生成snapshot和libflutter.so文件
1
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
FlutterPlugin插件过程分析
插件源码目录:flutter/packages/flutter_tools/gradle/flutter.gradle
从图中可了解到:
- 对于flutter engine的依赖,是通过关联其aar实现的
- debug编译时,Flutter的Dart工程,通过JIT编译,生成snapshot
- release编译时,Flutter的Dart工程,通过AOT编译,生成libapp.so
- release编译生成的libapp.so,通过打包成jar依赖
- flutter的其他数据,如字体等等文件,复制到apk的assets目录下
- Debug包的生成文件有:
- lib/xxx/libflutter.so
- assets/flutter_assets
- Release包的生成文件有:
- lib/xxx/libflutter.so
- lib/xxx/libapp.so
- assets/flutter_assets
总结
现有的add to app的一些问题:
- beta状态,只有master分支才支持,问题很多:
- .android文件夹执行flutter pub命令时,会被重新生成
- 同时master分支不稳定,无法生成可运行的release包
- 开发期间编译很耗时,同时编译两个工程
改造思路:
- 基于稳定分支,分离Flutter Dart编译与Flutter Native编译过程
- Flutter载体页支持usb或网络加载Flutter Dart的snapshot文件,并支持热更新
敬请期待后续…