如何修复Flutter项目中No signature of method: android()构建错误?
问题排查与修复方案
核心错误原因
你的项目存在两处关键配置错误:
android/app/build.gradle中,buildscript及对应依赖块被错误嵌套在android{}内部,Gradle无法识别该结构,直接触发android()方法签名不匹配的报错。pubspec.yaml使用了//作为注释符号,而YAML语法要求注释必须以#开头,这会导致依赖解析异常。
分步修复
1. 修正android/app/build.gradle结构
将buildscript块移至文件顶级位置(apply plugin语句之后、android{}之前),同时补充必要的仓库声明:
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 FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } // 移至顶级位置的buildscript块 buildscript { ext.kotlin_version = "1.6.0" repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:4.2.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 33 ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { applicationId "com.example.apitutorials" minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" }
2. 修正pubspec.yaml注释语法
将YAML中的//注释替换为符合语法要求的#:
name: apitutorials description: A new Flutter project. publish_to: 'none' version: 1.0.0+1 environment: sdk: '>=2.18.6 <3.0.0' dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 http: ^0.13.5 modal_progress_hud_nsn: ^0.3.0-nullsafety-1 image_picker: ^0.8.8 # flutter_plugin_android_lifecycle: ^2.0.15 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^2.0.0 flutter: uses-material-design: true
3. 验证修复
执行以下命令完成后续操作:
flutter clean:清理项目缓存flutter pub get:拉取正确依赖flutter run:重新运行项目
内容的提问来源于stack exchange,提问作者Ashish Jose
相关产品推荐
相关产品推荐

