我刚开始使用 Jetpack Compose 和 Hilt。但是当我注入 ViewModel 时遇到了问题。
我得到的错误:
java.lang.RuntimeException: Cannot create an instance of class com.example.chaes.login.viewModel.SignUpViewModel
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.chaes.login.viewModel.SignUpViewModel> has no zero argument constructor
我可以在 Activity 中注入一切都很好,但在 ViewModel 中却不行。我已经尝试了所有我能找到的解决方案。
我的毕业文件:
项目根级别:
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10"
classpath 'com.google.gms:google-services:4.3.8'
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.37'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
模块级别:
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
kapt{
correctErrorTypes true
}
dependencies {
...
// Hilt
implementation "com.google.dagger:hilt-android:2.37"
kapt "com.google.dagger:hilt-android-compiler:2.37"
...
}
我的申请文件
@HiltAndroidApp
class BaseApplication: Application() {
}
我的模块文件:
@Module
@InstallIn(SingletonComponent::class)
object AuthRepoModule {
@Singleton
@Provides
fun provideAuthRepo(): FirebaseAuthRepo{
return FirebaseAuthRepo()
}
@Singleton
@Provides
fun provideRandomString(): String{
return "gejifeg"
}
}
该项目是具有可组合屏幕的单个活动,因此 MainActivity:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() { ... }
视图模型:
@HiltViewModel
class SignUpViewModel @Inject constructor(
firebaseAuthRepo: FirebaseAuthRepo,
) : ViewModel() { ... }
我尝试过的事情:
- 更改为 ViewModelComponent 而不是 Singleton
- 更改为 kapt "com.google.dagger:hilt-compiler:2.37" 而不是 kapt "com.google.dagger:hilt-android-compiler:2.37"
- 删除构建文件夹并重建项目
- 使缓存无效并重新启动
编辑:找到解决方案! 正如@sitatech 在评论中提到的,需要使用 hiltViewModel() 而不是 viewModel() 来将 viewModel 提供给可组合。