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.
The shortcut
Treat the graph like a street map: every screen has an address, navigate drives there, popBackStack reverses.
Start
Stack:
plants. The host shows the list.
Drills
Answer fast — trust the rule.
Which object keeps the navigation back stack?
The graph has composable("plant/{id}"). Which call opens plant 12?
After saving, the add screen should return to the previous screen. What should it trigger?
Why pass onOpen to PlantListScreen rather than the NavController?
Remember
- The controller keeps the stack; the host maps routes to screens.
navigatepushes,popBackStackand Back pop.- Give screens callbacks, not the controller.
