Skip to the workspace
Pebellslearn by building
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.

android / Navigation with NavHost

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.