解决 Flutter 插件在 Android Studio 中的 Gradle 版本冲突

问题现象

在 Android Studio 中打开 Flutter 插件的 Android 目录时,遇到以下错误:

Build file '~/libpag/flutter-ext/android/build.gradle' line: 23
A problem occurred evaluating root project 'libpag_flutter'.
> 'org.gradle.api.artifacts.Dependency org.gradle.api.artifacts.dsl.DependencyHandler.module(java.lang.Object)'
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
Deprecated Gradle features were used in this build, making it incompatible with Gradle 10.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
For more on this, please refer to https://docs.gradle.org/9.0-milestone-1/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.

问题原因

这是典型的 Gradle 版本与 Android Gradle Plugin (AGP) 版本不兼容问题。

在 Android 项目中,有两个关键版本需要匹配:

  1. Gradle 版本:构建工具本身(如 7.5, 8.0, 9.0)

    • 定义在 gradle/wrapper/gradle-wrapper.properties
  2. AGP 版本:Android 专用插件

    • 定义在 build.gradleclasspath 'com.android.tools.build:gradle:x.x.x'

版本兼容关系:

Gradle 版本AGP 版本
7.4 - 7.67.3.0 - 7.4.2
8.0 - 8.38.0.0 - 8.1.4
8.4+8.2.0+

Flutter 插件的特殊性

Flutter 插件项目通常没有 gradle-wrapper.properties 文件,因为它依赖宿主应用的 Gradle 配置。

但在 Android Studio 中直接打开插件的 android 目录时,IDE 会将其视为独立项目,使用默认 Gradle 版本(可能是 9.0),导致与旧版 AGP 冲突。

解决方案

方案一:创建 gradle-wrapper.properties(推荐)

android/gradle/wrapper/ 目录下创建 gradle-wrapper.properties

1
2
3
4
5
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

方案二:升级 AGP 版本

修改 android/build.gradle

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
buildscript {
    ext.kotlin_version = '1.9.0'
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.android.tools.build:gradle:8.1.4'  // 升级到 8.1.4
    }
}

allprojects {  // 注意:去掉 rootProject
    repositories {
        google()
        mavenCentral()
    }
}

方案三:在 Android Studio 中配置

  1. 打开 File → Settings → Build Tools → Gradle
  2. 选择 Use Gradle from: ‘specified location’
  3. 指定或下载 Gradle 7.5

建议

对于 Flutter 插件开发,推荐方案一,改动最小且不影响插件在实际 Flutter 项目中的使用。

执行任一方案后,点击 Android Studio 的 Sync Now 重新同步项目即可。