[英]Cannot create ViewModel instance when using Hilt dependency injection
我剛開始使用 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 中注入。 我已經嘗試了我能找到的所有解決方案。
我的gradle文件:
項目根級別:
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() { ... }
我嘗試過的事情:
編輯:找到解決方案! 正如@sitatech 在評論中提到的,需要使用 hiltViewModel() 而不是 viewModel() 為可組合提供 viewModel 。
在應用模塊依賴添加
...
// Hilt
implementation "com.google.dagger:hilt-android:2.37"
kapt "com.google.dagger:hilt-android-compiler:2.37"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha03"
...
其他部分對我來說似乎還可以。
正如@sitatech 在評論中提到的,我需要在可組合中使用 hiltViewModel() 而不是 viewModel()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.