Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create an instance of ViewModel when using Hilt with Compose

I'm using Hilt with Jetpack Compose.

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val homeRepository: HomeRepository
): ViewModel() {

fun getCarDetails(): Car {
    return homeRepository.getCarDetails()
}
}

That's how I inject the repo.

@Module
@InstallIn(SingletonComponent::class)

abstract class DataModule {

    @Binds
    @Singleton
    abstract fun bindHomeRepository(
        homeRepository: HomeRepositoryImpl,
    ): HomeRepository
}

And that's my composable.

@Composable
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
    val carData = viewModel.getCarDetails()
    Column(
        Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        TopBar(carData = carData, modifier = Modifier)
        CarImage(carData = carData, modifier = Modifier)
    }
}

I've annotated my Activity with @AndroidEntryPoint. Can't figure out what's the problem. It crashes with a message:

java.lang.RuntimeException: Cannot create an instance of class com.example.carcontroller.ui.HomeViewModel

My library versions for compose is 1.2.1 and for hilt 2.43.2. Compose ViewModel version is 2.5.1.

EDIT: I fixed the crash and below answered how. Hope that will help someone.

like image 738
Hayk Mkrtchyan Avatar asked Oct 23 '25 00:10

Hayk Mkrtchyan


1 Answers

Well, the developer's page isn't updated yet.

There's a library called hilt navigation compose:

implementation "androidx.hilt:hilt-navigation-compose:1.0.0"

After syncing we need to use hiltViewModel() instead of viewModel() like this

fun HomeScreen(viewModel: HomeViewModel = hiltViewModel())

Now it's not crashing. Thank you.

like image 76
Hayk Mkrtchyan Avatar answered Oct 24 '25 15:10

Hayk Mkrtchyan