In Navigation 3, who owns the back stack, and how do NavDisplay, entryProvider and onBack turn that list into screens?
answer
- no controller, no graph
- keys, not screens, on the stack
- snapshot-state list drives recomposition
- key in, NavEntry out
- an empty list fails a require check
basics
~20 sIn Navigation 3 the app owns the back stack, an observable list of keys it edits. NavDisplay observes the list, asks entryProvider for each key's NavEntry, shows the top one and calls onBack when the user goes back.
solid answer
~40 sNavigation 3 has no `NavController` and no navigation graph. The back stack is a list of keys the app creates, usually with `rememberNavBackStack(...)` or as a `SnapshotStateList`, and navigation is list editing: `backStack.add(TankDetail(id))` goes forward, `backStack.removeLastOrNull()` goes back. `NavDisplay(backStack = ..., onBack = ..., entryProvider = ...)` observes that list and calls the `entryProvider`, typically built with `entryProvider { entry<TankDetail> { key -> ... } }`, to turn each key into a `NavEntry` that holds the composable content. By default it shows the last entry in a single pane. `onBack` runs when the user goes back; its default removes the last element when the list is a `MutableList`. NavDisplay only handles back while there is a previous entry, and it requires a non-empty list.
code
kotlin · 17 lines@Serializable data object TankGallery : NavKey
@Serializable data class TankDetail(val tankId: String) : NavKey
@Composable
fun AquariumNav() {
val backStack = rememberNavBackStack(TankGallery)
NavDisplay(
backStack = backStack,
onBack = { backStack.removeLastOrNull() },
entryProvider = entryProvider {
entry<TankGallery> {
TankGalleryScreen(onTankClick = { id -> backStack.add(TankDetail(id)) })
}
entry<TankDetail> { key -> TankDetailScreen(key.tankId) }
},
)
}go deeper
Recall the three pieces: an app-owned list of keys, an entryProvider that turns a key into a NavEntry, and NavDisplay that shows the top entry. Navigating forward is add, going back is removeLastOrNull.
Explain why the list must be snapshot state, what the default onBack does for a MutableList, and why NavDisplay disables its back handling on the first screen instead of popping it.
Show how owning the stack changes design: navigation from a ViewModel or test is list editing, unknown keys and duplicate entry registrations fail loudly, and an empty list is a crash you design out.
Frame the trade: an app-owned stack is ordinary state you can save, test and reshape, but the team now owns rules a controller used to enforce, such as never popping the root and keeping keys small and serializable.
## Who owns what Navigation 3 splits navigation into three parts, and only one of them is the library's state. - **The back stack** belongs to the app. It is a `List<T>` of **keys**: small values such as a `data object TankGallery` or a `data class TankDetail(val tankId: String)`. A key is a reference to content, not the content itself. - **The entry provider** belongs to the app too. It is a function from a key to a `NavEntry`, the class that pairs a key with its composable content and optional `metadata`. - **`NavDisplay`** is the composable that observes the list, resolves each key through the entry provider and renders the result, with transitions and predictive back. There is no `NavController`, no graph and no start destination declared up front. The first element of the list is the start destination, because the app put it there. ## The wiring, step by step 1. Create the stack. `rememberNavBackStack(TankGallery)` returns a `NavBackStack<NavKey>`, a `MutableList` that wraps a `SnapshotStateList` and implements `StateObject`, and saves itself across configuration changes and process death. A plain `remember { mutableStateListOf<Any>(TankGallery) }` also works for display, without the saving. 2. Describe the destinations with the `entryProvider` DSL: `entry<TankGallery> { ... }` registers content for every key of that class, and `entry<TankDetail> { key -> TankDetailScreen(key.tankId) }` receives the key itself, so arguments travel inside the key. 3. Hand both to `NavDisplay`, together with an `onBack` lambda. When the list changes, NavDisplay recomposes, maps the keys to entries and, with the default `SinglePaneSceneStrategy`, shows the last entry. ## Navigating is editing a list | What the user does | What the app does to the list | |---|---| | Opens a tank | `backStack.add(TankDetail("reef"))` | | Goes back | `backStack.removeLastOrNull()` | | Jumps to a fresh start | `backStack.clear()` then `backStack.add(TankGallery)` in the same event handler | | Replaces the top screen | `backStack[backStack.lastIndex] = TankDetail("koi")` | Because the list is **snapshot state**, any code that can reach it can navigate: a click handler, a `ViewModel` that holds the stack, a test. The list must be observable: a plain `ArrayList` changes silently and NavDisplay never recomposes. ## onBack and its default `onBack` is NavDisplay's callback for a completed system back. Its default is `{ if (backStack is MutableList<T>) backStack.removeLastOrNull() }`, so a `NavBackStack` or `SnapshotStateList` needs no lambda at all; an immutable `List` passed in needs one, or back does nothing to it. NavDisplay enables its back handling only while the current scene has **previous entries**. On the first screen it is disabled, so the back event goes on to the rest of the system, usually finishing the Activity (Activity behaviour is covered with Activities and Fragments). NavDisplay requires a non-empty list: if app code removes the last key itself, the next composition fails with `IllegalArgumentException` ("NavDisplay backstack cannot be empty"). ## Mistakes worth recognising - Keeping the stack in a non-snapshot list, so taps change data but never the screen. - Expecting a `navigate()` call: navigation is `add`, `remove` and assignment on the list. - Forgetting a destination: the DSL's default fallback throws `IllegalStateException` ("Unknown screen ...") for a key with no `entry`. - Registering `entry<TankDetail>` twice in one provider, which fails a `require` check with `IllegalArgumentException` while the provider is built. - Popping the last key in app code and crashing on the empty-list check. ## What NavDisplay does with each key On every change NavDisplay maps **all** keys on the list to entries through the provider, then hands the entries to its scene strategies; the default strategy renders only the last one. Content of entries that are not on screen is not composed, so a screen deep in the stack costs nothing until the user returns to it. NavDisplay also gives each rendered entry its own `LocalLifecycleOwner`: the top entry reaches `RESUMED` once the transition has settled, stays at `STARTED` while a transition runs or an overlay covers it, and an entry that was popped but is still animating out is held at `CREATED`. That replaces the per-destination lifecycle that Navigation Compose's back stack entries used to provide. ## Why it is built this way Owning the list makes the stack ordinary state: it can be saved, tested, restored from a deep link or split per tab without asking a controller. Navigation Compose's `NavHost` and `NavController` keep their own back stack and expose it through the controller; Navigation 3 inverts that, which is the difference interviewers usually probe first.
- What happens when the user presses back on the aquarium app's first screen?NavDisplay enables its back handling only while the current scene has previous entries. With only `TankGallery` on the stack it is disabled, so `onBack` is not called and the back event goes on to the system, which normally finishes the Activity. The default `onBack` therefore never empties the list. If app code removes the last key itself, NavDisplay throws `IllegalArgumentException` because its back stack cannot be empty.
- Why does a back stack kept in a plain mutableListOf never change the screen?NavDisplay recomposes when snapshot state it reads changes. An `ArrayList` from `mutableListOf` is not snapshot state, so `add` mutates it without notifying Compose and the old screen stays. Use `mutableStateListOf`, which returns a `SnapshotStateList`, or `NavBackStack`, which wraps one and implements `StateObject`.
- What does the entryProvider DSL do with a key it has no entry for?`entryProvider { }` takes a `fallback` parameter whose default throws `IllegalStateException("Unknown screen $key")`. Pass your own fallback to return an error `NavEntry` instead, or, better, make the key type a sealed hierarchy so every key has an `entry`. Registering the same class twice with `entry<K>` throws `IllegalArgumentException` when the provider is built.
The back stack is a pile of index cards the app holds in its own hand, each card naming a screen. NavDisplay is a projector that always shows the top card; the app changes the picture only by adding or removing cards, never by telling the projector where to go.
- Navigation 3 navigates by calling navigate() on a NavController that NavDisplay creates.
- NavDisplay keeps its own copy of the back stack that the app must keep in sync.
- Any Kotlin list works as the back stack, including a plain mutableListOf.
- The default onBack can pop the first screen and leave a blank NavDisplay.
- The entryProvider must declare a graph with a start destination.