androidkotlinandroid-jetpack-composeandroid-viewmodel

viewModels not found in jetpack compose


I am trying to use a delegate function with viewModels, but I'm encountering an issue when trying to import it.

@Composable
fun ImagePickerScreen() {
    val viewModel : ImageViewModel by viewModels
}

I've attempted to import all dependencies, but the delegate function still isn't importing.


Solution

  • You can only use by viewModels in the Android View system, not with Jetpack Compose. In Compose you have the viewModel() function that you can use as follows:

    @Composable
    fun ImagePickerScreen(viewModel: ImageViewModel = viewModel()) {
        // or declare it in function body
        // val viewModel: ImageViewModel = viewModel()
    }
    

    You will need the following dependency in your build.gradle:

    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5")
    

    If you use Navigation with a NavHost, this will return a ViewModel instance that is scoped to the current destination of the NavGraph.
    Otherwise, the instance will be scoped to the Activity.