Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 104 ยท Navigation

Navigation Compose Basics

Learn Navigation Compose: NavController, NavHost, type-safe routes with serializable destinations, navigate and popBackStack, plus a back stack simulator you can run.

A real app has more than one screen: a list, a detail page, a settings screen. In the View era you moved between them with fragments and a navigation graph in XML. In Compose there is no new activity per screen and no XML: screens are composable functions, and Navigation Compose decides which one is on display. It keeps a back stack of destinations, shows the top one, and pops it when the user presses Back.

This lesson introduces the three main pieces (NavController, NavHost and destinations), shows how to define routes in a type-safe way with @Serializable classes, and explains navigate and popBackStack. The Navigation code is read-only because it needs the Android SDK and the navigation library. The TryIts are stand-ins that implement a back stack and a route table in plain Kotlin, so you can see the mechanism. A refresher on screens and tasks is in Activities and setContent.

The big picture

There are three parts:

  • A destination is a screen identified by a route.
  • A NavHost is a composable that shows the current destination. You declare all destinations inside it as a graph.
  • A NavController holds the back stack and exposes navigate(...) and popBackStack(). You create it with rememberNavController().
flowchart LR
    U["User taps item"] --> N["navController.navigate(Detail(id = 7))"]
    N --> S["Back stack:<br/>Home, Detail 7"]
    S --> H["NavHost shows<br/>the top destination"]
    B["User presses Back"] --> P["popBackStack()"]
    P --> S2["Back stack: Home"]
    S2 --> H

The controller changes the back stack; the host always renders its top entry.

Defining routes the type-safe way

In older versions, routes were strings such as "detail/{id}", which are easy to mistype. Since Navigation 2.8, a route can be a Kotlin class or object marked @Serializable. The compiler checks that you pass the right arguments. This needs the Kotlin serialization plugin (see JSON with kotlinx.serialization and kotlinx.serialization basics).

Kotlin
// read-only example: needs the Android SDK, Navigation Compose 2.8+ and the serialization plugin
@Serializable object Home
@Serializable data class Detail(val id: Int)
@Serializable object Settings

Use object for destinations without arguments and data class for destinations that need data. The properties of the class are the arguments of the route.

Put the controller and the host in your top-level composable:

Kotlin
// read-only example
@Composable
fun AppNavigation() {
    val navController = rememberNavController()

    NavHost(navController = navController, startDestination = Home) {
        composable<Home> {
            HomeScreen(
                onOpenDetail = { id -> navController.navigate(Detail(id)) },
                onOpenSettings = { navController.navigate(Settings) },
            )
        }
        composable<Detail> { backStackEntry ->
            val detail: Detail = backStackEntry.toRoute()
            DetailScreen(id = detail.id, onBack = { navController.popBackStack() })
        }
        composable<Settings> {
            SettingsScreen(onBack = { navController.navigateUp() })
        }
    }
}

Some details worth knowing:

  • startDestination is the first screen and the root of the back stack.
  • composable<Detail> registers a destination for that route class. backStackEntry.toRoute() rebuilds the Detail object with its argument.
  • navigate(Detail(id)) pushes a new entry on the stack.
  • popBackStack() removes the top entry and returns true if something was removed (and false if the stack was already empty).
  • navigateUp() is the "Up" action of the app bar. Inside one app it behaves like Back, but it can also leave your app when your destination was reached through a deep link.

The system Back button already calls popBackStack() for you through the activity's back dispatcher; you rarely handle it yourself.

Do not pass the NavController around

Pass lambdas like onOpenDetail: (Int) -> Unit to screens, not the NavController. A screen that depends on a NavController cannot be previewed or tested without one, and it knows too much about the rest of the app. The NavHost is the only place where navigation calls are wired up. This is the same state hoisting idea from State Hoisting and Unidirectional Data Flow: the screen reports an event and the owner decides what to do.

A back stack simulator

The stand-in below implements the core of the controller: a list of routes with a navigate that pushes and a popBackStack that pops. Routes are sealed classes, just as @Serializable classes are in the real library. Pressing Back on the last entry leaves the app.

Kotlin A back stack simulator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The Detail(7) entry carries its argument in the entry itself, which is why the screen can be rebuilt with the same data when you come back to it.

Destinations and the graph

NavHost builds a navigation graph: a set of destinations, each of which knows how to render itself. A destination that does not exist is an error: in the real library, navigating to a route that is not declared throws an IllegalArgumentException. With type-safe routes you rarely hit this, because the compiler knows the classes, but you still need to register each one in the NavHost.

The second stand-in models the graph as a map from route type to a composable-like function and shows what happens with a missing destination. It also demonstrates one more rule: each navigate creates a new entry, even for the same route class, so navigating to the same detail twice puts two entries on the stack (the next lessons show how to avoid it).

Kotlin A destination table and duplicate entries (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Passing NavController into screens. Pass lambdas.
  • Creating the controller more than once. Call rememberNavController() once, high in the tree, so the back stack survives recomposition and configuration changes.
  • Calling navigate during composition. Call it from event handlers (clicks) or from a LaunchedEffect, not directly in the composable body, or it runs on every recomposition.
  • Forgetting that every navigate pushes a new entry; rapid double taps can push twice. Use launchSingleTop as shown in Back Stack, Launch Modes and Deep Links.
  • Using string routes in new code. Type-safe routes catch mistakes at compile time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the job of NavHost?

    NavHost is the composable that displays the current destination and contains the destinations of the graph; the NavController holds the back stack.
  2. 2. How do you define a destination that needs an Int argument in type-safe navigation?

    From Navigation 2.8, a @Serializable class or object is a route; the class properties are the arguments, and the compiler checks them.
  3. 3. What does popBackStack() return when only the start destination is left?

    popBackStack removes the top entry and returns whether it did something; with only the root entry left it returns false and the system Back button closes the app.
  4. 4. Why pass lambdas like onOpenDetail to a screen instead of the NavController?

    A screen that only reports events can be used in previews and tests without a navigation setup, and the NavHost keeps all navigation decisions in one place.

Summary

  • Navigation Compose has destinations, a NavHost that renders the top of the back stack, and a NavController that changes the stack.
  • Type-safe routes are @Serializable objects and data classes; properties are arguments, read back with toRoute().
  • navigate(route) pushes, popBackStack() pops, navigateUp() is the app bar action.
  • Create the controller once with rememberNavController(), and keep it out of screens: pass lambdas.
  • Every navigate creates a new entry, which later lessons refine with launch modes.
  • The Navigation code is read-only here; the TryIts model the back stack and the destination table.

Next: Passing Arguments and Results