androidandroid-jetpack-compose

Where is the "viewModel()" method in Androids Compose State documentation coming from?


Androids compose / state documentation contains a sample referring to a mysterious viewModel() function or method, but as the documentation has left out all import statements I can't for the life of me figure out where this function is coming from..

enter image description here


Solution

  • You can check the official doc:

    you can access a ViewModel from any composable by calling the viewModel() function.

    To use the viewModel() functions,add the androidx.lifecycle:lifecycle-viewmodel-compose:$latestVersion dependency to your build.gradle file.

    Finally use:

    import androidx.lifecycle.viewmodel.compose.viewModel