[Dagger-Hilt] Can't get viewModel in composable by Hilt
Anatoly4444 opened this issue · 6 comments
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/ }) {
}
}`
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.