skip to content

In a Navigation Compose shopping app with bottom tabs, how do popUpTo with saveState, launchSingleTop and restoreState keep the cart tab's back stack when users switch tabs?

level: seniorimportance: should knowfreq 55%

answer

  1. one NavController, many saved stacks
  2. pop to the graph's start
  3. save on the way out
  4. restore on the way back
  5. no duplicate tab roots

basics

~20 s

On each tab tap, navigate with popUpTo(the graph's start destination) { saveState = true }, launchSingleTop = true and restoreState = true. Leaving the cart pops and saves its stack; returning restores Cart and Checkout with their saved state.

solid answer

~40 s

With plain `navigate(CartGraph)` every tab tap pushes onto one back stack: Back walks through every tab ever visited and repeated taps stack duplicates. The fix goes in the bottom bar's click handler: `navController.navigate(tab.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true }; launchSingleTop = true; restoreState = true }`. `popUpTo` removes everything above the start destination, and `saveState` saves those entries (their arguments and `rememberSaveable` state, such as a lazy list's scroll position) and keeps their `ViewModel`s instead of destroying them. `launchSingleTop` stops a second copy of the tab's root. `restoreState` brings back whatever was saved for the tab you navigate to, so Cart and Checkout come back as the user left them. Model each tab as a nested graph so its whole stack saves as one unit.

code

kotlin · 28 lines
kotlin
import androidx.navigation.NavDestination.Companion.hasRoute
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination

@Composable
fun ShopBottomBar(navController: NavHostController, tabs: List<TopTab>) {
    val entry by navController.currentBackStackEntryAsState()
    NavigationBar {
        tabs.forEach { tab ->
            val selected = entry?.destination?.hierarchy
                ?.any { it.hasRoute(tab.route::class) } == true
            NavigationBarItem(
                selected = selected,
                onClick = {
                    navController.navigate(tab.route) {
                        popUpTo(navController.graph.findStartDestination().id) {
                            saveState = true
                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                },
                icon = { Icon(tab.icon, contentDescription = tab.label) },
                label = { Text(tab.label) },
            )
        }
    }
}

go deeper

for a junior

Recall the three options in the tab click handler, popUpTo with saveState, launchSingleTop and restoreState, and what the user sees without them.

for a middle

Explain one controller holding several saved stacks, what popUpTo pops, and why each tab should be a nested graph with its own start destination.

for a senior

Show the production edges: ViewModels kept while saved, scroll positions restored per entry, reselection behaviour, clearing saved stacks on sign-out and highlighting tabs through the hierarchy.

for a principal

Weigh multiple saved stacks against a single linear history for the product, and set one shared tab-navigation helper so every screen behaves the same.

## The problem A shopping app has three bottom tabs: **Home**, **Search** and **Cart**. Inside Cart the user goes Cart -> Checkout (address step). They switch to Home to look at a product, then tap Cart again. They expect to land on Checkout with the address they typed, and Back from Home should leave the app rather than replay their tab history. A `NavController` holds **one back stack**. If the bottom bar just calls `navController.navigate(CartGraph)`, each tap pushes another destination on top of that one stack: - Back walks through every tab the user visited, in order. - Tapping the current tab again pushes a duplicate of its root. - Coming back to Cart creates a fresh Cart screen; Checkout and its typed address are gone. ## The pattern Navigation supports **multiple back stacks** inside one controller through three `NavOptions`: ```kotlin navController.navigate(tab.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } ``` | Option | What it does here | |---|---| | `popUpTo(startId)` | pops everything above the graph's start destination before navigating, so the stack never grows past one tab | | `saveState = true` (inside `popUpTo`) | saves the popped entries and their state instead of destroying them | | `launchSingleTop = true` | at most one copy of the tab's destination on top, like the activity single-top flag | | `restoreState = true` | restores any state previously saved for the destination being navigated to; no effect if none was saved | ## What "saved" means When entries are popped with `saveState = true`, the controller: 1. moves each entry to `CREATED` and records its state (arguments and saved state); 2. **does not clear the entries' `ViewModel`s**, which are cleared only when an entry is popped without saving; 3. keeps the saveable state of each destination. `NavHost` gives every back stack entry its own saveable-state provider, so values in `rememberSaveable`, including a `rememberLazyListState()` scroll position, are stored per entry. The saved stacks are also written into the controller's own saved state, and `rememberNavController()` stores the controller with `rememberSaveable`, so the tabs' stacks survive a configuration change and process death. ## Make each tab a nested graph Give each tab a **nested graph** whose start destination is the tab's root: ```kotlin navigation<CartGraph>(startDestination = Cart) { composable<Cart> { /* ... */ } composable<Checkout> { /* ... */ } } ``` The bottom bar navigates to `CartGraph`. Saving and restoring then happen per graph: the whole Cart -> Checkout stack is saved under the cart graph and restored as a unit. To highlight the selected tab, read `navController.currentBackStackEntryAsState()` and check `destination.hierarchy.any { it.hasRoute(tab.route::class) }`, so the Cart icon stays selected while Checkout is showing. ## Edge cases to know - **Re-tapping the selected tab.** With this pattern the tab's stack is popped, saved and restored again, so the user typically stays on Checkout. If the product wants a re-tap to return to the tab's root, handle reselection separately, for example with `popBackStack<Cart>(inclusive = false)`. - **Signing out.** Saved stacks outlive the visible UI. Clear one with `navController.clearBackStack<CartGraph>()`, or navigate with `popUpTo` without `saveState`, so a new user never restores the old checkout. - **Which id the stack is saved under.** `saveState` stores the stack under the `popUpTo` destination when `inclusive` is true, or under the last destination popped when it is false, and `restoreState` looks it up by the destination you navigate to. Popping to the graph's start destination and navigating to the tab's graph keeps those two in step. ## How to check it works A quick manual script catches most mistakes in this pattern: 1. Open Cart, go to Checkout and type part of an address. 2. Switch to Home, scroll the product grid, then switch back to Cart: Checkout should reappear with the typed text. 3. Switch to Home again: the grid should be at the scroll position you left. 4. Press Back from Home: the app should leave rather than replay the tabs. 5. Rotate the device and enable "Don't keep activities" in the developer options, then repeat steps 2 to 4: the saved stacks should survive both. If step 2 shows a fresh Cart, `saveState` or `restoreState` is missing or the stack was saved under a different destination. If step 4 walks through tabs, `popUpTo` is missing. ## Where this sits The same mechanics exist for Fragment destinations in XML (`app:popUpToSaveState`, `app:restoreState`), outside this answer. How navigation should be modelled as state across platforms is covered in the mobile system design material; this is how Navigation Compose implements it.

  • After saving and restoring the Cart tab in Navigation Compose, is the Checkout screen's ViewModel the same instance?
    Yes, within the same process. Popping with `saveState = true` keeps the entries' `ViewModel` stores instead of clearing them, and `restoreState` reattaches the restored entries to them. After process death the `ViewModel` is recreated, but its saved state handle and the screen's `rememberSaveable` values come back from the saved stack.
  • How do you stop a signed-out user's saved checkout stack from being restored for the next user in Navigation Compose?
    Clear it explicitly. `navController.clearBackStack<CartGraph>()` drops the state saved for that graph; do the same for every tab graph. Then navigate to sign-in with a `popUpTo` that does not set `saveState`, so the stack being left is destroyed instead of saved and nothing from the old session can be restored.

Like a browser with one window and several tabs: switching tabs parks a tab's history rather than closing it, and switching back reopens the exact page you were on.

  • Each tab needs its own NavHost and NavController to keep separate stacks
  • launchSingleTop alone keeps each tab's back stack
  • saveState destroys the popped entries' ViewModels and keeps only their arguments
  • restoreState fails with an exception if no state was saved
  • Tab history is kept in memory only and is lost on process death