添加Hilt依赖时遇IllegalStateException:不支持的元数据版本
问题
添加Hilt依赖时触发错误:java.lang.IllegalStateException: Unsupported metadata version. Check that your Kotlin version is >= 1.0
配置信息
模块级build.gradle(plugins)
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'kotlin-kapt' id 'realm-android' id 'androidx.navigation.safeargs.kotlin' id 'kotlin-parcelize' }
模块级build.gradle(dependencies)
//Dependency injection with Hilt implementation("com.google.dagger:hilt-android:2.38.1") kapt("com.google.dagger:hilt-android-compiler:2.38.1") implementation 'androidx.core:core-ktx:1.8.0' implementation 'androidx.appcompat:appcompat:1.4.2' implementation 'com.google.android.material:material:1.6.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
项目级build.gradle
buildscript { dependencies { classpath 'com.android.tools.build:gradle:7.2.1' classpath "io.realm:realm-gradle-plugin:10.11.1" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10" classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0" classpath "com.google.dagger:hilt-android-gradle-plugin:2.42" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } plugins { id 'com.android.application' version '7.2.1' apply false id 'com.android.library' version '7.2.1' apply false id 'org.jetbrains.kotlin.android' version '1.7.0' apply false } task clean(type: Delete) { delete rootProject.buildDir }
已尝试多个社区解决方案但无效,现寻求后续可行方案。
解决办法
- 统一Kotlin版本:项目级build.gradle中两处Kotlin版本不一致,一处是buildscript里的
kotlin-gradle-plugin:1.6.10,另一处是plugins块的kotlin-android:1.7.0,将两者改为同一版本(建议用1.7.0):
// buildscript dependencies部分 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0" // plugins部分 id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
对齐Hilt全组件版本:当前Hilt的android库(2.38.1)、编译器(2.38.1)和gradle插件(2.42)版本不匹配,统一为同一版本(比如2.42):
- 模块级dependencies修改:
implementation("com.google.dagger:hilt-android:2.42") kapt("com.google.dagger:hilt-android-compiler:2.42")- 项目级buildscript dependencies保持:
classpath "com.google.dagger:hilt-android-gradle-plugin:2.42"彻底清理缓存并重构:
- 打开Android Studio,依次点击
File -> Invalidate Caches...,选择Invalidate and Restart - 删除项目根目录下的
.gradle、build文件夹,以及各模块内的build文件夹 - 执行终端命令
./gradlew clean build重新构建项目
- 打开Android Studio,依次点击
补充Kapt配置:在模块级build.gradle的android块内添加kapt配置,确保注解处理器正常工作:
android { // 其他已有配置... kapt { correctErrorTypes = true } }
内容的提问来源于stack exchange,提问作者Goku
相关产品推荐
相关产品推荐

