You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成Firestore遇D8单Dex文件方法数超限问题求助

解决D8: Cannot fit requested classes in a single dex file (# methods: 71610 > 65536) 错误

你遇到的是Android开发中非常常见的Dex方法数超限问题——当你的应用(包含所有依赖库)的方法总数超过单个Dex文件允许的65536个上限时,就会触发这个构建错误。Firestore本身依赖了大量Google服务相关的库,很容易让方法数突破这个阈值,这也是为什么你之前的应用没遇到、这次新集成Firestore就出问题的原因。

下面是针对你现有配置的具体修复步骤:

步骤1:修改app级build.gradle,启用MultiDex

打开项目中的android/app/build.gradle文件,完成两处关键修改:

1.1 在defaultConfig块中开启MultiDex

找到defaultConfig代码块,添加multiDexEnabled true配置,修改后如下:

defaultConfig {
    applicationId "com.boody.sag.bakery"
    minSdkVersion 16
    targetSdkVersion 28
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    // 添加这一行,启用MultiDex
    multiDexEnabled true
}

1.2 添加MultiDex依赖库

在dependencies代码块中添加multidex的支持依赖:

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    // 添加MultiDex依赖
    implementation 'com.android.support:multidex:1.0.3'
}

步骤2:(可选但推荐)指定cloud_firestore稳定版本

你的pubspec.yaml中cloud_firestore未指定版本,可能会拉取兼容性未知的最新版本,建议指定一个适配你Flutter SDK的稳定版本,示例如下:

dependencies:
  cloud_firestore: ^2.5.4 # 可根据你的Flutter版本调整具体版本号
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2

步骤3:清理缓存并重新构建

为确保修改生效,执行以下操作:

  • 点击Android Studio顶部菜单栏的File > Invalidate Caches / Restart,重启IDE
  • 在终端运行flutter clean命令清理构建缓存
  • 重新运行你的Flutter应用

额外说明

如果你的应用自定义了Application类(即继承自Application的自定义类),还需要补充以下操作:

  • 将自定义Application类的父类改为MultiDexApplication
  • 或者在attachBaseContext方法中调用MultiDex.install(this):
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

从你提供的配置来看,你没有自定义Application类,所以这一步可以跳过。

完成以上修改后,你的应用会生成多个Dex文件来容纳超过64K的方法,就能顺利解决这个构建错误了。

内容的提问来源于stack exchange,提问作者Don

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:15:53