google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.35k stars 2k forks source link

[Dagger-Hilt] Can't get viewModel in composable by Hilt #4279

Open Anatoly4444 opened 2 months ago

Anatoly4444 commented 2 months ago

Hilt can't provide View Model by factory using viewModel() function in composable function. Every time I got:

Caused by: java.lang.NoSuchMethodException: com.example.myapplication.HomeViewModel.<init>

My ViewModel class @HiltViewModel class HomeViewModel @Inject constructor(val testClass: TestClass) : ViewModel() { fun test() { testClass.test() } }

Composable: `@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun HomeScreen( modifier: Modifier = Modifier, viewModel: HomeViewModel = viewModel() ) { Button(onClick = { /TODO/ }) {

} }`

danysantiago commented 2 months ago

This should work and is mentioned in the Compose + Hilt docs: https://developer.android.com/develop/ui/compose/libraries#hilt

Please double check your setup, that the Activity or Fragment are annotated with @AndroidEntryPoint. That your runtime and annotation processor dependencies are in the module and that the Hilt Gradle plugin is applied.