当在flutter项目中引入了firebase组件后,运行以下命令:

  • flutter run
  • flutter build apk

会出现下文的报错信息。

D8: Cannot fit requested classes in a single dex file (# methods: 84722 > 65536)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForRelease'.
> com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: 
PROJECT_PATH\build\app\intermediates\transforms\dexBuilder\release\0.jar,
PROJECT_PATHbuild\app\intermediates\transforms\dexBuilder\release\1.jar, 
PROJECT_PATH\build\app\intermediates\transforms\dexBuilder\release\2.jar,
PROJECT_PATH\build\app\intermediates\transforms\dexBuilder\release\3.jar,
···
PROJECT_PATH\build\app\intermediates\transforms\dexBuilder\release\319.jar
  The number of method references in a .dex file cannot exceed 64K.
  Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

* 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

BUILD FAILED in 3m 4s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                     186.7s (!)
Gradle task assembleRelease failed with exit code 1

其中有一句

The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

不仅告诉了我们错误原因,而且给出了解决办法。
现在按照文档中的方案,在app/build.gradle内下下文部分做如下修改。

 defaultConfig {
        applicationId "YOUR_APPLICATION_ID"
        // minSdkVersion 16
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

然后重新运行命令。出现了如下报错信息。

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes.
···

该问题是由于依赖库版本不一致引发的。本例中出问题的组件为exifinterface
解决办法是在project/build.gradle内结尾部分加入如下代码。

不过,在最新的firebase组件中,不会再出现这个问题了,可以不进行这一步操作

subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.name == 'exifinterface'  && !details.requested.name.contains('multidex') ) {
                details.useVersion "1.0.0"
            }
        }
    }
}