一.创建flutter模块
如果已经有flutter模块,此步骤可忽略
1.Android Studio 选择 New Flutter Project 创建 flutter 时,要选择Module,不能是 Application
2.创建完毕后,没有 .android 和.ios两个目录,此时可执行:
flutter pub get
执行完毕以后,正常情况下,就会生成 .android 和.ios两个目录,此时模块创建完毕。
二.Android项目引入flutter模块
1.在Android项目的settings.gradle 中,添加如下内容:
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir.parentFile,
'flutter_module/.android/include_flutter.groovy'
))
evaluate中的flutter_module为flutter模块路径,需要根据自身情况进行设置。
2.在Android项目子模块下的build.gradle中添加flutter模块依赖:
dependencies {
implementation project(':flutter') // 固定是':flutter'
}
自此,集成flutter模块完毕。
将 Flutter module 作为依赖项
问题记录
在集成flutter模块以后,编译出现如下问题:
- Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin class ‘FlutterPlugin’.
- Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration
当前环境:
1.Flutter (Channel stable, 3.19.3, on Microsoft Windows [版本 10.0.18363.657], locale zh-CN)(执行fluter doctor,基于flutter_windows_3.16.5-stable)
2.Android Studio Giraffe | 2022.3.1
新建的android工程后,默认是使用compose,gradle版本是8.0,插件和依赖的仓库配置放在了settings.gradle中,如下:
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
而根目录下的build.gradle中的配置只有如下内容:
plugins {
id 'com.android.application' version '8.1.0' apply false
id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
}
对于 问题1:Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin class ‘FlutterPlugin’.
解决方法:在settings.gradle中将 repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 的 RepositoriesMode.FAIL_ON_PROJECT_REPOS 改为 RepositoriesMode.PREFER_PROJECT, 如下
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.PREFER_PROJECT)
repositories {
google()
mavenCentral()
}
}
这样允许flutter模块设置依赖仓库,关于RepositoriesMode说明如下:
- FAIL_ON_PROJECT_REPOS
If this mode is set, any repository declared directly in a project, either directly or via a plugin, will trigger a build error.- PREFER_PROJECT
If this mode is set, any repository declared on a project will cause the project to use the repositories declared by the project, ignoring those declared in settings.- PREFER_SETTINGS
If this mode is set, any repository declared directly in a project, either directly or via a plugin, will be ignored.
对于 问题2:Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration
解决方法:
由于上面设置成了PREFER_PROJECT,导致settings中设置的依赖仓库无效,因此需要在根目录下的build.gradle中,申请依赖仓库
allprojects {
repositories {
google()
mavenCentral()
}
}