Navigation with NavHost
Sprout now has a list, a detail screen and an add screen. You could make each one an activity, as in the intents section. Modern Compose apps usually keep one activity and switch screens inside it with the Navigation library. The back stack idea you already know stays exactly the same.
The rule
The controller keeps the stack; the host maps routes to screens.
Two pieces work together:
NavController— owns the navigation back stack. You callnavigateto push a destination andpopBackStackto go back.NavHost— the area of the screen that shows the current destination. It holds the graph: a list of routes and the composable for each.
val nav = rememberNavController()
NavHost(navController = nav, startDestination = "plants") {
composable("plants") {
PlantListScreen(onOpen = { id -> nav.navigate("plant/$id") })
}
composable("plant/{id}") { entry ->
val id = entry.arguments?.getString("id")
PlantDetailScreen(id)
}
composable("add") {
AddPlantScreen(onSaved = { nav.popBackStack() })
}
}- A route is the destination's address.
{id}is a placeholder filled bynavigate("plant/7"). - System Back pops the navigation stack automatically.
- Screens receive callbacks such as
onOpeninstead of the controller itself, which keeps them easy to preview and test.
Recent versions of Navigation Compose also let you use @Serializable classes as routes, such as PlantDetail(id = 7), so the compiler checks the arguments. The idea is identical: a route, a screen, a stack.