flutter build aar时"Android property not found."问题

android端在执行flutter build aar命令时,有时候会遇到如下错误(问题版本1.17.1,目前最新的flutter版本1.22.4已不存在此问题)

FAILURE: Build failed with an exception.

  • Where:

    Initialization script '....\packages\flutter_tools\gradle\aar_init_script.gradle' line: 15

    aar_init_script.gradle中修改相关代码如下
void configureProject(Project project, String outputDir) {
    if (!project.hasProperty("android")) {
        throw new GradleException(project.toString())
        // throw new GradleException("Android property not found.")
    }
    ...
}

再次执行flutter build aar,可定位到具体出错插件项目。如:
引入path_provider:1.6.8的项目,执行以上命令时会有如下错误信息提示

  • What went wrong:

    project ':path_provider_macos'

    由此猜测可能是某些插件依赖了macos相关,查看path_provider-1.6.8中的pubspec.yaml,可发现其依赖了path_provider_macos
dependencies:
  flutter:
    sdk: flutter
  path_provider_platform_interface: ^1.0.1
  path_provider_macos: ^0.0.4

目前我们的项目中这三个插件path_provider:1.6.8、shared_preferences: 0.5.7+2、webview_flutter: 0.3.22+1
都会有同样的"Android property not found."问题。

在网上搜了一下,大部分解决办法都是说临时删除掉.pub-cache/hosted/pub.flutter-io.cn下出错的相关包,
这个的确可以解决,但下次执行flutter clean, flutter pub get后,再次执行flutter build aar时还会有同样的问题,
于是想看能否看下源码了解下有没有好的解决办法。

在flutter的packages/flutter_tools/gradle/flutter.gradle中,看到如下项目配置的代码

/**
 * Configures the Flutter plugin dependencies.
 *
 * The plugins are added to pubspec.yaml. Then, upon running `flutter pub get`,
 * the tool generates a `.flutter-plugins` file, which contains a 1:1 map to each plugin location.
 * Finally, the project's `settings.gradle` loads each plugin's android directory as a subproject.
 */
private void configurePlugins() {
    if (!buildPluginAsAar()) {
        getPluginList().each this.&configurePluginProject
        getPluginDependencies().each this.&configurePluginDependencies
        return
    }
    project.repositories {
        maven {
            url "${getPluginBuildDir()}/outputs/repo"
        }
    }
    getPluginList().each { pluginName, pluginPath ->
        configurePluginAar(pluginName, pluginPath, project)
    }
}

配置插件依赖部分的代码如下,其会过滤掉不支持android platform的依赖插件

// Add the dependencies on other plugin projects to the plugin project.
// A plugin A can depend on plugin B. As a result, this dependency must be surfaced by
// making the Gradle plugin project A depend on the Gradle plugin project B.
private void configurePluginDependencies(Object dependencyObject) {
    ...
    dependencyObject.dependencies.each { pluginDependencyName ->
        ...
        Project dependencyProject = project.rootProject.findProject(":$pluginDependencyName")
        if (dependencyProject == null ||
            !doesSupportAndroidPlatform(dependencyProject.projectDir.parentFile.path)) {
            return
        }
        // Wait for the Android plugin to load and add the dependency to the plugin project.
        pluginProject.afterEvaluate {
            pluginProject.dependencies {
                implementation dependencyProject
            }
        }
    }
}

关键代码doesSupportAndroidPlatform如下,主要是判断插件项目中是否有android目录和android/build.gradle文件

// Returns `true` if the given path contains an `android/build.gradle` file.
//
// TODO(egarciad): Fix https://github.com/flutter/flutter/issues/39657.
// Android Studio may create empty android directories due to the logic in /android/settings.gradle,
// which imports all plugins regardless of whether they support the android platform.
private Boolean doesSupportAndroidPlatform(String path) {
    File editableAndroidProject = new File(path, 'android' + File.separator + 'build.gradle')
    return editableAndroidProject.exists()
}

根据之前代码configurePlugins中的注释,我们大概了解项目中插件配置流程如下

1.首先在pubspec.yaml中添加相关插件

2.执行flutter pub get命令生成.flutter-plugins文件

3.项目的settings.gradle加载每一个插件的android目录作为子项目

在.android项目中,我们先查看生成的settings.gradle文件

// Generated file. Do not edit.
include ':app'

rootProject.name = 'android_generated'
setBinding(new Binding([gradle: this]))
evaluate(new File(settingsDir, 'include_flutter.groovy'))

再查看生成的文件include_flutter.groovy,部分代码如下

def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot, '.flutter-plugins')
if (pluginsFile.exists()) {
    pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}

plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.toPath().resolve(path).resolve('android').toFile()
    gradle.include ":$name"
    gradle.project(":$name").projectDir = pluginDirectory
}

其先从.flutter-plugins文件中加载插件,然后配置插件项目作为subproject
其中可以看到,在添加插件的android目录作为子目录时,并未判断插件是否含有android目录,
这样上面的path_provider_macos就会被添加到子项目中作为依赖项目,然后在构建时校验失败。

projectsEvaluated {
    ...
    // Gets the plugin subprojects.
    Set modulePlugins = rootProject.subprojects.findAll {
        it.name != "flutter" && it.name != "app"
    }
    // When a module is built as a Maven artifacts, plugins must also be built this way
    // because the module POM's file will include a dependency on the plugin Maven artifact.
    // This is due to the Android Gradle Plugin expecting all library subprojects to be published
    // as Maven artifacts.
    modulePlugins.each { pluginProject ->
        configureProject(pluginProject, moduleProject.property("output-dir"))
        moduleProject.android.libraryVariants.all { variant ->
            // Configure the `assembleAar` task for each plugin's projects and make
            // the module's equivalent task depend on the plugin's task.
            String variantName = variant.name.capitalize()
            moduleProject.tasks.findByPath("assembleAar$variantName")
                .dependsOn(pluginProject.tasks.findByPath("assembleAar$variantName"))
        }
    }
}

大概了解依赖配置流程后,我们可以想到如下解决办法

1.修改include_flutter.groovy中的插件项目配置规则,加上android目录的校验

2.修改aar_init_script.gradle中的配置规则

具体修改如下:

1.include_flutter.groovy是通过模版生成的,修改的话可修改flutter下packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl

plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.toPath().resolve(path).resolve('android').toFile()
    if (pluginDirectory.exists()) {
        gradle.include ":$name"
        gradle.project(":$name").projectDir = pluginDirectory
    } else {
        println("plugins " + name + " pluginDirectory : " + pluginDirectory + " does not exist")
    }
}

2.修改flutter下文件packages/flutter_tools/gradle/aar_init_script.gradle中projectsEvaluated配置部分代码:

    Set modulePlugins = rootProject.subprojects.findAll {
        it.name != "flutter" && it.name != "app" && it.hasProperty("android")
    }

以上两个方式都需要修改flutter中的代码,暂时没找到更好的解决方法,有了解其他解决办法的,也希望分享下。

追记:
flutter 1.22.4版本生成的include_flutter.groovy中代码变更

gradle.apply from: "$flutterSdkPath/packages/flutter_tools/gradle/module_plugin_loader.gradle"

查看module_plugin_loader.gradle代码可见其中添加插件依赖时,检查了是否支持android

def pluginsFile = new File(moduleProjectRoot, '.flutter-plugins-dependencies')
if (pluginsFile.exists()) {
    def object = new JsonSlurper().parseText(pluginsFile.text)
    assert object instanceof Map
    assert object.plugins instanceof Map
    assert object.plugins.android instanceof List
    // Includes the Flutter plugins that support the Android platform.
    object.plugins.android.each { androidPlugin ->
        assert androidPlugin.name instanceof String
        assert androidPlugin.path instanceof String
        def pluginDirectory = new File(androidPlugin.path, 'android')
        assert pluginDirectory.exists()
        include ":${androidPlugin.name}"
        project(":${androidPlugin.name}").projectDir = pluginDirectory
    }
}

你可能感兴趣的:(flutter build aar时"Android property not found."问题)