这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战
一、背景
如何把Flutter当成库集成进原生项目
大部分项目都是已经存在的,新建Flutter工程重写整个项目是不切实际的。
在这种情况下,Flutter可以作为模块(源码)或 库(aar的方式)集成到现有的项目中。然后可以将该模块导入到原生(Android或IOS)项目中,共享Dart语言写的业务逻辑。
二 源码集成步骤
1.1 新建Android项目
这个不用说了吧。。
1.2 build.gradle 添加java8的依赖
因为Flutter使用了Java8的功能, 所以这里我们的原生Android应用也要支持java8.
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
复制代码
1.3 创建flutter module
1.4 导入flutter module
- 先在settings.gradle 里加上以下代码
Properties properties = new Properties()
def dependFlutterSource = false
if (file('local.properties').canRead()) {
properties.load(new FileInputStream(file('local.properties')))
dependFlutterSource = properties.getProperty('dependFlutterSource', 'false').toBoolean()
}
setBinding(new Binding([gradle: this]))
def flutter_path = 'flutter_module/.android/include_flutter.groovy'
evaluate(new File(settingsDir,flutter_path))
复制代码
dependFlutterSource
是定义在项目下local.properties
里的,这个文件是不会被提交到git的。所以项目组中负责Flutter开发的同学只需要在里面设置dependFlutterSource=true
即可,如果是原生开发,
1.5 依赖flutter module
在app下的build.gradle添加对 flutter 的依赖
1.6 运行
- 通过新的Window窗口打开刚才新建的flutter_module
- 清单文件配置下Activity的路径,就可以正常跳转到FlutterActivity了。
<activity android:name="io.flutter.embedding.android.FlutterActivity"/>
复制代码
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
initView()
}
private fun initView() {
findViewById<View>(R.id.btn2).setOnClickListener {
startActivity(Intent(this, FlutterActivity::class.java))
}
}
}
复制代码
三 aar集成步骤
3.1 只需要修改上面步骤1.5
...
Properties properties = new Properties()
def dependFlutterSource = false
if (project.rootProject.file('local.properties').canRead()) {
properties.load(new FileInputStream(project.rootProject.file('local.properties')))
dependFlutterSource = properties.getProperty('dependFlutterSource', 'false').toBoolean()
}
dependencies {
...
if (dependFlutterSource) {
api project(path: ':flutter')
} else {
api '你的远程flutter module 路径'
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END