Flutter构建APK提示更新Kotlin Gradle插件 更新后仍报错如何解决
问题诱因
- 配置执行顺序错误。Gradle按脚本从上到下的顺序加载配置,你在代码中先执行
apply plugin: 'kotlin-android'加载Kotlin Gradle插件,在文件末尾才声明ext.kotlin_version = '1.6.21',插件初始化阶段完全读取不到你定义的版本参数,仍然使用默认的低版本配置触发报错。 - 核心构建配置块缺失。你贴出的
build.gradle没有buildscript代码块,Android构建插件、Kotlin插件、Firebase相关插件的类路径依赖没有声明在构建脚本依赖段,Gradle无法按预期拉取对应版本的构建插件。 - 旧缓存干扰。修改配置后如果没有完全终止正在运行的Gradle进程、清理根目录下的Gradle缓存文件夹,旧的插件元数据会被持续复用,导致配置修改不生效。
解决步骤
- 调整
android/build.gradle的文件结构,把构建脚本配置、版本声明移动到文件最顶部,参考如下正确配置:
buildscript { ext.kotlin_version = '1.6.21' def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } 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.") } repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:4.1.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.10' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1' } } allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.crashlytics' android { compileSdkVersion 31 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { applicationId "com.iqonic.kivicare" minSdkVersion 21 targetSdkVersion 31 versionCode 9 versionName "3.5.0" multiDexEnabled true } googleServices { disableVersionCheck = true } buildTypes { release { signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation platform('com.google.firebase:firebase-bom:26.6.0') implementation 'com.google.firebase:firebase-crashlytics' implementation 'com.google.firebase:firebase-analytics' implementation 'androidx.multidex:multidex:2.0.1' }
注意要删除原来写在文件末尾的ext.kotlin_version = '1.6.21'声明,避免重复定义。
- 彻底清理缓存后重新构建,按顺序执行以下操作:
- 执行
./gradlew --stop终止所有正在运行的Gradle后台进程 - 手动删除项目根目录、android目录下的
.gradle缓存文件夹和build输出文件夹 - 执行
flutter clean清理Flutter构建缓存 - 执行
flutter pub get拉取项目依赖后,重新尝试构建APK
- 若仍报错,检查
android/gradle/wrapper/gradle-wrapper.properties中的Gradle版本:使用上述配置时,Gradle版本需要对应为6.5~6.7.1区间,版本差过大也会触发插件版本兼容错误。
内容的提问来源于stack exchange,提问作者Nile Okomo
相关产品推荐
相关产品推荐

