Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injection of an @HiltViewModel class is prohibited since it does not create a ViewModel instance correctly

I am trying to inject a ViewModel annotated with @HiltViewModel into a Fragment and get the following error:

Injection of an @HiltViewModel class is prohibited since it does not create a ViewModel instance correctly.
  Access the ViewModel via the Android APIs (e.g. ViewModelProvider) instead.
  Injected ViewModel: com.example.MyViewModel

Is that meaning I should not use Hilt to inject ViewModels into Fragments? - Or is an old warning already fixed in newest versions of the library.

like image 530
Pablo Valdes Avatar asked Dec 07 '25 08:12

Pablo Valdes


1 Answers

You can use

val taskViewModel: ComposeStudyViewModel by viewModels()

instead of using one with ViewModelProvider

https://developer.android.com/training/dependency-injection/hilt-jetpack

like image 158
Thracian Avatar answered Dec 11 '25 14:12

Thracian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!