首页 > 解决方案 > 我的 Flutter 应用程序中的 app/Appbuild.grandle 错误

问题描述

* 我开始在 Flutter 中开发(IDE:Android Studio),每当我想修改 app/build.gradle 时都会出错

def localProperties = new  Properties()

def flutterRoot = localProperties.getProperty('flutter.sdk')

if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") 
}

我知道它不会影响编译应用程序,但是应用程序 / bradle 带有红色下划线非常烦人

标签: androidflutterbuild.gradle

解决方案


解决方案只是删除异常。但是,问题可能是由于安装flutter的文件夹权限不足。确保您拥有正确的权限。

最后,您可以通过将部分文件替换为以下内容来重写您的 build.gradle 文件以使其没有异常:

安卓/build.gradle

subprojects {
    buildDir = "${rootProject.buildDir}/${project.name}"

    beforeEvaluate {
        def localProps = new Properties().tap { prop ->
            File localPropsFile = getRootProject().file('local.properties')
            if (localPropsFile.exists()) {
                localPropsFile.withReader("utf-8") {
                    prop.load(it)
                }
            }
        }

        localProps.stringPropertyNames().each { key ->
            ext[key] = localProps.getProperty(key)
        }
    }
}

本质上,它的作用是读取local.properties文件(如果存在)并在子项目的命名空间中创建从中读取的属性。我们基本上是在模拟 gradle 对gradle.properties文件的处理。

android/app/build.gradle

ext {
    flutterRoot = properties.'flutter.sdk'
    flutterVersionCode = properties.'flutter.versionCode' ?: '1'
    flutterVersionName = properties.'flutter.versionName' ?: '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

... // everything else is pretty much the same from here

现在在子项目中,我们可以使用项目的属性访问这些属性。上面的代码用更类似于 gradle 的东西替换了那些可怕的 if 语句大杂烩。


推荐阅读