Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 104 ยท Navigation

Bottom Navigation and Nested Graphs

Build Android bottom navigation with one back stack per tab, group screens into nested navigation graphs, model auth flows and scope a ViewModel to a graph.

Most apps with more than a couple of sections show a bottom navigation bar: Home, Search, Profile and so on. Users expect two things from it. Each tab remembers where you were (if you scroll deep into Search, switch to Profile and come back, Search is exactly as you left it), and the Back button behaves predictably. Meanwhile, the code gets crowded: dozens of destinations need structure, and multi-step flows such as sign-up or checkout need to share data between their screens.

This lesson shows how Navigation Compose handles all of it: NavigationBar with one back stack per tab, nested graphs that group related screens, auth flows that you leave for good, and a ViewModel scoped to a graph. It continues from Back Stack, Launch Modes and Deep Links, where saveState and restoreState were introduced. The real Compose and Navigation code is read-only (it needs the Android SDK), and the TryIt blocks are runnable stand-ins that model the same behavior in plain Kotlin.

A NavigationBar holds NavigationBarItems. Each item is selected when the current destination belongs to its tab, and clicking it navigates to the tab's root:

Kotlin
// read-only example: needs Compose Material 3 and Navigation Compose
@Serializable object Feed
@Serializable object Search
@Serializable object Profile

enum class Tab(val route: Any, val label: String, val icon: ImageVector) {
    FEED(Feed, "Feed", Icons.Default.Home),
    SEARCH(Search, "Search", Icons.Default.Search),
    PROFILE(Profile, "Profile", Icons.Default.Person),
}

@Composable
fun AppScaffold() {
    val navController = rememberNavController()
    val entry by navController.currentBackStackEntryAsState()
    val destination = entry?.destination

    Scaffold(
        bottomBar = {
            NavigationBar {
                Tab.entries.forEach { tab ->
                    NavigationBarItem(
                        selected = destination?.hierarchy?.any { it.hasRoute(tab.route::class) } == true,
                        onClick = {
                            navController.navigate(tab.route) {
                                popUpTo(navController.graph.findStartDestination().id) {
                                    saveState = true
                                }
                                launchSingleTop = true
                                restoreState = true
                            }
                        },
                        icon = { Icon(tab.icon, contentDescription = null) },
                        label = { Text(tab.label) },
                    )
                }
            }
        },
    ) { padding ->
        NavHost(navController, startDestination = Feed, modifier = Modifier.padding(padding)) {
            composable<Feed> { FeedScreen() }
            composable<Search> { SearchScreen() }
            composable<Profile> { ProfileScreen() }
        }
    }
}

Three details deserve attention:

  • currentBackStackEntryAsState() turns the current entry into Compose state, so the bar recomposes when the destination changes.
  • destination.hierarchy walks up from the current destination through its parent graphs. Checking the hierarchy (instead of only the current destination) keeps the Search tab highlighted when you are three screens deep inside it.
  • The navigate options are the recipe from the previous lesson: pop up to the start destination while saving state, avoid duplicates, and restore state if the tab was visited before. Without saveState and restoreState, switching tabs would reset each tab to its root.

Depending on window size, the same tabs can be shown as a bottom bar, a navigation rail or a drawer. Adaptive Layouts and Window Size Classes covers NavigationSuiteScaffold, which switches between them for you.

One back stack per tab

What does the saved state actually look like? Each tab behaves like its own small stack, and the NavController keeps the stacks of tabs you left. Back pops within the current tab. When the tab is at its root, Back by convention moves to the start tab, and Back from the start tab leaves the app.

flowchart TB
    subgraph Feed["Feed tab"]
        F1["Feed"] --> F2["Article 12"]
    end
    subgraph Search["Search tab"]
        S1["Search"] --> S2["Results: kotlin"] --> S3["Article 40"]
    end
    subgraph Profile["Profile tab"]
        P1["Profile"]
    end

Each tab owns a stack. Switching tabs stores the current stack and restores the target's.

The stand-in below keeps a map from tab to stack, stores and restores them as you switch, and applies the Back rules just described. It is a model of the behavior, not the real library.

Kotlin A multi-back-stack tab navigator (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.

Check the line after the second switch search: the search stack still holds results/kotlin and article/40. That is exactly what saveState and restoreState accomplish in the real library. Reselecting the current tab pops it to its root, which is a common convention, though you decide whether to implement it.

Nested graphs

A nested graph is a group of destinations with its own start destination, declared with navigation. It is just another entry in the parent graph, so you navigate to the whole group by navigating to its route:

Kotlin
// read-only example: grouping the sign-in screens
@Serializable object AuthGraph
@Serializable object Login
@Serializable object Register
@Serializable object ForgotPassword
@Serializable object MainGraph

NavHost(navController, startDestination = AuthGraph) {
    navigation<AuthGraph>(startDestination = Login) {
        composable<Login> { LoginScreen(onLoggedIn = { /* leave the graph, see below */ }) }
        composable<Register> { RegisterScreen() }
        composable<ForgotPassword> { ForgotPasswordScreen() }
    }
    navigation<MainGraph>(startDestination = Feed) {
        composable<Feed> { FeedScreen() }
        composable<Search> { SearchScreen() }
        composable<Profile> { ProfileScreen() }
    }
}

Nested graphs help in several ways:

  • Organization. In a large app each feature module exposes one graph, usually through an extension function like NavGraphBuilder.authGraph(navController).
  • Hierarchy checks. The bottom bar can check hierarchy against a graph route, not each screen.
  • Leaving a flow. You can pop the whole group at once: popUpTo<AuthGraph> { inclusive = true } removes every screen of the graph.
  • Scoped state. Entries of the graph can share a ViewModel (next sections).

Auth flows

An auth flow is a flow you want to leave behind. The user signs in, lands on the main screens, and pressing Back must not show the login form again. Likewise, signing out should wipe the main stack. Both directions use nested graphs and popUpTo:

Kotlin
// read-only example: crossing between graphs
// after sign-in:
navController.navigate(MainGraph) {
    popUpTo<AuthGraph> { inclusive = true }
}

// after sign-out:
navController.navigate(AuthGraph) {
    popUpTo<MainGraph> { inclusive = true }
}

Where does the decision "is the user signed in?" live? Not in the NavHost scattered across screens: keep it in one place, for example a SessionViewModel that exposes a StateFlow of the sign-in status. The top of the app observes it and chooses startDestination (or navigates when the status changes). The details of state holders come in ViewModel.

ViewModels scoped to a graph

By default viewModel() inside a destination creates a ViewModel scoped to that one back stack entry: it is created when the entry is first shown and cleared when the entry is popped. That is right for most screens. A multi-step flow is different: the three sign-up screens need to share the typed name and email, but nobody else should see them.

The trick is to ask for the ViewModel using the graph's back stack entry as the owner:

Kotlin
// read-only example: one ViewModel for the whole sign-up flow
navigation<SignupGraph>(startDestination = SignupName) {
    composable<SignupName> { entry ->
        val parentEntry = remember(entry) { navController.getBackStackEntry<SignupGraph>() }
        val vm: SignupViewModel = viewModel(parentEntry)
        NameStep(vm.state, onNext = { navController.navigate(SignupEmail) })
    }
    composable<SignupEmail> { entry ->
        val parentEntry = remember(entry) { navController.getBackStackEntry<SignupGraph>() }
        val vm: SignupViewModel = viewModel(parentEntry)   // the same instance
        EmailStep(vm.state, onDone = { navController.navigate(SignupDone) })
    }
}

Both screens receive the same instance because the owner is the graph's entry, which lives as long as at least one of its destinations is on the back stack. When the user leaves the flow (completing it with popUpTo<SignupGraph> { inclusive = true }, or backing out of the first step), the graph entry is removed and the ViewModel is cleared. With Hilt, hiltViewModel(parentEntry) does the same. Scope to a graph only for state that is truly flow-wide, not as a way to share things globally.

The next stand-in models those lifetimes: a scope is created when the first screen of a graph is pushed and cleared when the last one is popped.

Kotlin Graph-scoped state with lifetimes (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.

Notice that going back one screen keeps the data, while leaving the whole flow clears it, and a new run of the flow starts empty. If you ever see the previous run's data in a new flow, the scope was wider than the flow.

Common mistakes

  • Checking only the current destination for the selected tab, so the tab loses its highlight on inner screens. Check the hierarchy.
  • Navigating to tabs without saveState/restoreState, which resets every tab on each switch.
  • Putting the auth check in each screen. Keep one source of truth and navigate on state change.
  • Scoping a ViewModel to the activity when it only matters for one flow. It never gets cleared.
  • Forgetting launchSingleTop on the bar, so repeated taps pile duplicates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a bottom bar check destination.hierarchy instead of only the current destination?

    hierarchy includes the parent graphs, so a screen nested in a tab's graph still counts as belonging to that tab.
  2. 2. Which pair of navigate options gives each tab its own remembered back stack?

    saveState stores the popped entries and their UI state, and restoreState brings them back when the tab is selected again.
  3. 3. After signing in, how do you make sure Back does not return to the login screen?

    Popping the auth graph inclusively removes all of its screens, so the first Back from the main flow leaves the app instead.
  4. 4. Three sign-up screens must share a ViewModel that disappears when the flow ends. What is the right owner?

    The graph entry lives while any of its destinations is on the back stack and is removed with the flow, so the ViewModel is shared during the flow and cleared afterwards.

Summary

  • A NavigationBar selects tabs through currentBackStackEntryAsState() and destination.hierarchy.
  • Switching tabs with popUpTo(start) { saveState = true }, launchSingleTop and restoreState gives every tab its own back stack.
  • Back pops within a tab; at a tab root it usually goes to the start tab, then leaves the app.
  • Nested graphs (navigation<...>) group screens, shorten hierarchy checks and can be popped as a unit.
  • Auth flows are separate graphs: cross between them with popUpTo inclusive so Back cannot return.
  • viewModel(graphEntry) shares one ViewModel across a flow and clears it when the flow ends.
  • The Compose and Navigation code is read-only; the TryIts model tab stacks and scope lifetimes in plain Kotlin.

Next: Architecture Layers: UI, Domain and Data