Flutter集成Firebase时Gradle构建失败,寻求解决方法
解决Flutter集成Firebase时Gradle plugins块报错问题
错误原因
报错提示only buildscript {}, pluginManagement {} and other plugins {} script blocks are allowed before plugins {} blocks, no other statements are allowed,本质是Gradle语法规范限制:所有plugins {}代码块必须放在pluginManagement {}或buildscript {}块之后,且在它们之前不能存在任何其他代码(比如独立注释、变量定义、import语句等)。
解决方案
1. 确认文件与代码位置
操作对象是app级build.gradle文件(路径:android/app/build.gradle),调整plugins {}块的位置:
- 确保文件最顶部仅保留
pluginManagement {}(若有)和buildscript {}(若有)块 - 将
plugins {}块移动到这两个块之后,且前面不能有任何无关代码
2. 正确代码示例
以下是符合规范的文件结构:
// 仅允许pluginManagement或buildscript块在最顶部 pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() } } buildscript { ext.kotlin_version = '1.9.0' repositories { google() mavenCentral() } dependencies { classpath "com.android.tools.build:gradle:7.4.2" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } // plugins块必须放在上述块之后,前面无其他代码 plugins { id 'com.android.application' id 'kotlin-android' id 'dev.flutter.flutter-gradle-plugin' id 'com.google.gms.google-services' // Firebase登录所需的Google服务插件 } // 所有其他配置(android、dependencies等)放在plugins块之后 android { namespace "com.example.your_app" compileSdk 34 defaultConfig { applicationId "com.example.your_app" minSdk 21 targetSdk 34 versionCode 1 versionName "1.0" } } dependencies { // 项目依赖配置 }
3. 额外注意事项
- 不要在
plugins {}块前添加独立注释行,注释需放在对应代码块内部 - Firebase的
google-services插件必须添加在app级build.gradle中,项目级build.gradle无需重复添加
内容的提问来源于stack exchange,提问作者Álvaro Lagoa
相关产品推荐
相关产品推荐

