How to use NavController in compose ViewModel via hilt

I am using jetpack compose with the navigation compose library to navigate from one screen to the next. Usually you would have a ViewModel that would take care of user interactions (e.g.: viewModel.addItem()). In order to fulfill the addItem command i would like to show another screen via navController.navigate(). The ViewModel itself is injected into the Composable via hiltNavGraphViewModel().

Not the question is: How could i inject the NavController into the ViewModel via hilt?

@HiltViewModel
class ScreenViewModel @Inject constructor(
  private val navController: NavController // where does it come from?
) : ViewModel() {

  fun showScreen() {
    navController.navigate("route")
  }

}

The NavController is created via the rememberNavController() method up in the composable hirarchy. I also do not want to pass the controller down the composable hierarchy or use a CompositionLocal. The preferred approach would be to have the controller available in the ViewModel.



Read more here: https://stackoverflow.com/questions/67382801/how-to-use-navcontroller-in-compose-viewmodel-via-hilt

Content Attribution

This content was originally published by Moritz at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: