Android Studio连接Firebase遇build.gradle报错:buildscript需在plugins块前
问题修复方案
错误原因
错误提示已明确说明:all buildscript {} blocks must appear before any plugins {} blocks in the script,即**buildscript代码块必须放在所有plugins代码块之前**,你当前根目录的build.gradle将plugins块写在了buildscript块前面,违反了Gradle的语法规则。
修复步骤
1. 修正根目录build.gradle
把buildscript块移到plugins块之前,修正后的代码如下:
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() // Google's Maven repository mavenCentral() // Maven Central repository } dependencies {// Add the dependency for the Google services Gradle plugin classpath 'com.google.gms:google-services:4.3.15' } } plugins { id 'com.android.application' version '8.0.2' apply false id 'com.android.library' version '8.0.2' apply false } allprojects { repositories {// Make sure that you have the following two repositories google() // Google's Maven repository mavenCentral() // Maven Central repository } }
2. 修正app模块build.gradle
你当前的app模块代码复制了根目录的内容,这是错误的,app模块需要配置自身的应用信息,正确示例如下:
plugins { id 'com.android.application' id 'com.google.gms.google-services' // 应用Firebase的Google服务插件 } android { namespace "com.yourpackage.myweb" // 替换为你的应用包名 compileSdk 34 defaultConfig { applicationId "com.yourpackage.myweb" // 替换为你的应用包名 minSdk 21 targetSdk 34 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { // 添加Firebase实时数据库依赖(可根据需求调整) implementation 'com.google.firebase:firebase-database:20.3.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.10.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
3. 同步项目
修改完成后,点击Android Studio右上角的Sync Now按钮,同步Gradle配置即可解决该编译错误。
内容的提问来源于stack exchange,提问作者Niru 15
相关产品推荐
相关产品推荐

