Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Navigation and App Structure  ›  Lesson

Navigation with NavHost

Navigation Components 16 minA NavController holds the screen back stack and a NavHost maps routes to composable screens, so one activity can host a whole app's screens.

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 call navigate to push a destination and popBackStack to 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 by navigate("plant/7").
  • System Back pops the navigation stack automatically.
  • Screens receive callbacks such as onOpen instead 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.

List → Monstera → BackStep 1 of 4
  1. Start

    Stack: plants. The host shows the list.

Drills

Answer fast — trust the rule.

quick drill

Which object keeps the navigation back stack?

quick drill

The graph has composable("plant/{id}"). Which call opens plant 12?

quick drill

After saving, the add screen should return to the previous screen. What should it trigger?

quick drill

Why pass onOpen to PlantListScreen rather than the NavController?

Remember

  • The controller keeps the stack; the host maps routes to screens.
  • navigate pushes, popBackStack and Back pop.
  • Give screens callbacks, not the controller.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWire Sprout's routes

Sprout has three screens: the plant list, a plant detail screen that needs a plant ID, and an add-plant screen. Describe the NavHost setup, how the list opens the detail for plant 7, and how the add screen returns after saving.