Skip to main content

Mobile development · Intermediate · 28 min

Navigate between Compose screens with Navigation 3

By Padding · Updated 18 Nov 2026
Eclipse Temurin JDK 25 · Kotlin 2.4.21 · Android Gradle Plugin 9.5.3 · Gradle 9.9.2 · Compose BOM 2026.11.01 · Navigation 3 1.2.2 · Lifecycle 2.11.1

You will build a two-tab recipe app in Jetpack Compose with Navigation 3 1.2, where the back stack is a list you own, screens are typed serializable keys that carry their arguments, each recipe screen has its own ViewModel, each tab keeps its own history, and the system back gesture is handled, with the navigation logic proved by Gradle unit tests.

On this page

Navigation 3 is Jetpack's newer navigation library for Compose, and it starts from a different idea to the Navigation Compose 2.x you may know. There is no NavController holding a back stack you cannot see. The back stack is a plain Kotlin list that your code owns: each item is a key that describes one screen, opening a screen means adding a key, and going back means removing the last one. NavDisplay watches that list and shows whatever is on top.

Because the stack is yours, the interesting navigation rules, such as "each tab remembers where you were" and "back from the Profile tab returns to Recipes", become ordinary Kotlin you can unit test without a phone.

In this tutorial you build Pantry, a small recipe app with two tabs. The Recipes tab has a list and a detail screen that takes the recipe ID as an argument and keeps a servings counter in its own ViewModel. The Profile tab has a screen for editing a display name that asks before throwing away unsaved changes when the reader presses back. You work in ~/pantry-nav-demo, a throwaway folder, and prove the keys, the ViewModel and the tab logic with Gradle unit tests. Running the app on a phone is the last, optional step.

If you are on prepaid mobile data, note that the first build downloads several hundred megabytes of Gradle plugins and libraries. Use Wi-Fi for steps 1 to 3; later builds reuse the cache.

Step 1 · Install the SDK packages this app compiles against

Compose UI 1.13, which the November 2026 Compose BOM brings in, must be compiled against Android API 37.1, and the Navigation 3 ViewModel integration needs at least API 37. Android Gradle Plugin 9.5 uses SDK Build Tools 36.0.0 by default. Check your tools, then install both packages:

Bash
echo "$ANDROID_HOME"
gradle --version
sdkmanager --install "platforms;android-37.1" "build-tools;36.0.0"
sdkmanager --list_installed

If echo "$ANDROID_HOME" prints an empty line or sdkmanager is not found, finish the SDK steps in Build your first Android screen with Kotlin and Jetpack Compose first. If sdkmanager asks you to accept a licence, read it and answer y. Recent command-line tools print a deprecation warning that points to the new android sdk command; sdkmanager still installs the packages.

Check it worked

gradle --version reports Gradle 9.9.2 (any 9.6 or newer is fine), and the installed list includes build-tools/36.0.0 and platforms/android-37.1 (older command-line tools print them as build-tools;36.0.0 and platforms;android-37.1).

Step 2 · Create the project with the Navigation 3 libraries

Navigation 3 comes in three artifacts, and each has one job:

  • navigation3-runtime holds the data side: the NavKey marker interface, NavBackStack, rememberNavBackStack and the entry DSL.
  • navigation3-ui holds NavDisplay, the composable that draws the top of the stack and animates between screens, including the predictive back animation.
  • lifecycle-viewmodel-navigation3, which ships with Lifecycle rather than Navigation, gives each screen on the stack its own ViewModelStore.

The project also adds lifecycle-runtime-compose for collectAsStateWithLifecycle(), the same way the state tutorial collects a StateFlow.

Keys are saved with kotlinx.serialization, so the project also applies the Kotlin serialization compiler plugin. Write the settings, the version catalog and the root build file:

Bash
mkdir -p ~/pantry-nav-demo/gradle
cd ~/pantry-nav-demo

cat > settings.gradle.kts <<'EOF'
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}
rootProject.name = "Pantry"
include(":app")
EOF

cat > gradle/libs.versions.toml <<'EOF'
[versions]
agp = "9.5.3"
kotlin = "2.4.21"
composeBom = "2026.11.01"
activityCompose = "1.13.0"
navigation3 = "1.2.2"
lifecycle = "2.11.1"
serialization = "1.13.0"
junit = "4.13.2"

[libraries]
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-compose-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-navigation3-runtime = { group = "androidx.navigation3", name = "navigation3-runtime", version.ref = "navigation3" }
androidx-navigation3-ui = { group = "androidx.navigation3", name = "navigation3-ui", version.ref = "navigation3" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-navigation3 = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-navigation3", version.ref = "lifecycle" }
kotlinx-serialization-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-core", version.ref = "serialization" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
junit = { group = "junit", name = "junit", version.ref = "junit" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
EOF

cat > build.gradle.kts <<'EOF'
plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.kotlin.compose) apply false
    alias(libs.plugins.kotlin.serialization) apply false
}
EOF

cat > gradle.properties <<'EOF'
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
android.useAndroidX=true
EOF

Now the app module and its manifest:

Bash
cd ~/pantry-nav-demo
mkdir -p app/src/main/kotlin/com/example/pantry app/src/test/kotlin/com/example/pantry

cat > app/build.gradle.kts <<'EOF'
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.compose)
    alias(libs.plugins.kotlin.serialization)
}

android {
    namespace = "com.example.pantry"
    compileSdk {
        version = release(37) { minorApiLevel = 1 }
    }
    defaultConfig {
        applicationId = "com.example.pantry"
        minSdk = 24
        targetSdk = 37
        versionCode = 1
        versionName = "1.0"
    }
    buildFeatures {
        compose = true
    }
}

dependencies {
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.compose.material.icons.core)
    implementation(libs.androidx.activity.compose)
    implementation(libs.androidx.navigation3.runtime)
    implementation(libs.androidx.navigation3.ui)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.androidx.lifecycle.runtime.compose)
    implementation(libs.androidx.lifecycle.viewmodel.navigation3)
    implementation(libs.kotlinx.serialization.core)

    testImplementation(libs.junit)
    testImplementation(libs.kotlinx.serialization.json)
}
EOF

cat > app/src/main/AndroidManifest.xml <<'EOF'
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:label="Pantry"
        android:theme="@android:style/Theme.Material.Light.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
EOF

There is no org.jetbrains.kotlin.android plugin: Android Gradle Plugin 9 compiles Kotlin itself. The Compose and serialization compiler plugins share the Kotlin version, and declaring them also sets the Kotlin version the build uses. kotlinx-serialization-json is only a test dependency; the app itself never writes JSON, but the tests use it to show what a key looks like when it is saved.

Check it worked

Bash
cd ~/pantry-nav-demo
gradle --console=plain :app:dependencies --configuration debugRuntimeClasspath | grep -E 'navigation3-(runtime|ui):' | sort -u

The first run takes several minutes while Gradle downloads the Android Gradle Plugin and the libraries. You should see lines such as +--- androidx.navigation3:navigation3-ui:1.2.2 and androidx.navigation3:navigation3-runtime:1.2.2. An error that mentions android-37.1 means the SDK package from step 1 is missing.

Step 3 · Describe each screen as a serializable key

A key is a small value that says which screen to show and with what arguments. A screen with no arguments is a data object; a screen that needs an argument is a data class that carries it. Every key implements NavKey and is marked @Serializable, because rememberNavBackStack writes the whole stack into Android's saved state. When a low-memory phone kills your app in the background, which happens often on budget Android devices, the reader comes back to the same screen with the same recipe open.

Create the keys and the recipe data:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/Keys.kt <<'EOF'
package com.example.pantry

import androidx.navigation3.runtime.NavKey
import kotlinx.serialization.Serializable

// Recipes tab
@Serializable
data object RecipeList : NavKey

@Serializable
data class RecipeDetail(val recipeId: String) : NavKey

// Profile tab
@Serializable
data object ProfileHome : NavKey

@Serializable
data object EditName : NavKey
EOF

cat > app/src/main/kotlin/com/example/pantry/Recipes.kt <<'EOF'
package com.example.pantry

data class Recipe(
    val id: String,
    val name: String,
    val from: String,
    val minutes: Int,
    val servings: Int,
)

val recipes = listOf(
    Recipe("jollof-rice", "Jollof rice", "West Africa", minutes = 75, servings = 6),
    Recipe("githeri", "Githeri", "Kenya", minutes = 90, servings = 4),
    Recipe("bobotie", "Bobotie", "South Africa", minutes = 60, servings = 6),
    Recipe("thieboudienne", "Thiéboudienne", "Senegal", minutes = 120, servings = 8),
)

/** Returns the recipe with [id], or null when there is none. */
fun findRecipe(id: String): Recipe? = recipes.firstOrNull { it.id == id }
EOF

RecipeDetail carries only the recipe's ID, not the whole Recipe. A key should be small and stable: it is saved to disk, compared with equals, and may outlive the data it points to. The screen looks the recipe up from the ID and handles the case where it no longer exists. The name Thiéboudienne has an accented letter on purpose, so you see non-ASCII text flow through your screens early.

Now a test that shows what Navigation 3 stores for each key:

Bash
cd ~/pantry-nav-demo
cat > app/src/test/kotlin/com/example/pantry/KeysTest.kt <<'EOF'
package com.example.pantry

import kotlinx.serialization.json.Json
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

class KeysTest {
    @Test
    fun detailKeyKeepsItsArgumentWhenSaved() {
        val key = RecipeDetail(recipeId = "githeri")
        val saved = Json.encodeToString(RecipeDetail.serializer(), key)

        assertEquals("""{"recipeId":"githeri"}""", saved)
        assertEquals(key, Json.decodeFromString(RecipeDetail.serializer(), saved))
    }

    @Test
    fun objectKeyComesBackAsTheSameObject() {
        val saved = Json.encodeToString(RecipeList.serializer(), RecipeList)

        assertEquals(RecipeList, Json.decodeFromString(RecipeList.serializer(), saved))
    }

    @Test
    fun unknownIdsFindNoRecipe() {
        assertNull(findRecipe("no-such-recipe"))
        assertEquals("Thiéboudienne", findRecipe("thieboudienne")?.name)
    }
}
EOF
gradle --console=plain testDebugUnitTest

Navigation 3 uses its own saved-state format rather than JSON, but the principle is the same: a key is turned into plain data and back, so everything in it must be serializable. A key that holds a lambda, a Context or a large list will fail to save.

Check it worked

The run ends with BUILD SUCCESSFUL. Open app/build/reports/tests/testDebugUnitTest/index.html in a browser: KeysTest shows 3 tests and 0 failures. If you remove @Serializable from RecipeDetail, the build fails with an unresolved reference to serializer; put it back.

Step 4 · Keep each recipe screen's state in its own ViewModel

The detail screen lets the reader change the number of servings. That number belongs to one recipe screen: open Githeri, set it to 5, open Bobotie from somewhere else, and each screen should keep its own count. When the reader goes back and the Githeri screen leaves the stack, its state should be thrown away.

That is what a ViewModel scoped to a stack entry gives you. With the rememberViewModelStoreNavEntryDecorator you add in the next step, each entry on the back stack gets its own ViewModelStore, and that store is cleared when the entry is popped. Write the ViewModel:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/RecipeViewModel.kt <<'EOF'
package com.example.pantry

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

/** State for one recipe screen. The recipe ID comes from the RecipeDetail key. */
class RecipeViewModel(recipeId: String) : ViewModel() {
    val recipe: Recipe? = findRecipe(recipeId)

    private val _servings = MutableStateFlow(recipe?.servings ?: 0)
    val servings: StateFlow<Int> = _servings.asStateFlow()

    fun addServing() {
        _servings.update { it + 1 }
    }

    fun removeServing() {
        _servings.update { (it - 1).coerceAtLeast(1) }
    }
}
EOF

The test below does by hand what the decorator does for you: one ViewModelStore per screen, and clear() when the screen is popped.

Bash
cd ~/pantry-nav-demo
cat > app/src/test/kotlin/com/example/pantry/RecipeViewModelTest.kt <<'EOF'
package com.example.pantry

import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test

class RecipeViewModelTest {
    private fun factoryFor(recipeId: String) =
        viewModelFactory { initializer { RecipeViewModel(recipeId) } }

    @Test
    fun servingsStartFromTheRecipeAndNeverDropBelowOne() {
        val viewModel = RecipeViewModel("githeri")
        assertEquals(4, viewModel.servings.value)

        viewModel.addServing()
        assertEquals(5, viewModel.servings.value)

        repeat(10) { viewModel.removeServing() }
        assertEquals(1, viewModel.servings.value)
    }

    @Test
    fun eachScreenHasItsOwnViewModel() {
        val githeriStore = ViewModelStore()
        val bobotieStore = ViewModelStore()
        val githeri = ViewModelProvider(githeriStore, factoryFor("githeri"))[RecipeViewModel::class.java]
        val bobotie = ViewModelProvider(bobotieStore, factoryFor("bobotie"))[RecipeViewModel::class.java]

        githeri.addServing()

        assertEquals(5, githeri.servings.value)
        assertEquals(6, bobotie.servings.value)
        // Asking the same store again returns the same instance, as after a rotation.
        assertSame(githeri, ViewModelProvider(githeriStore, factoryFor("githeri"))[RecipeViewModel::class.java])
    }

    @Test
    fun clearingTheStoreClearsTheViewModel() {
        val store = ViewModelStore()
        val viewModel = ViewModelProvider(store, factoryFor("bobotie"))[RecipeViewModel::class.java]
        var cleared = false
        viewModel.addCloseable(AutoCloseable { cleared = true })

        store.clear() // what happens when the entry is popped

        assertTrue(cleared)
    }
}
EOF
gradle --console=plain testDebugUnitTest

This ViewModel survives rotation, but not the process being killed: the servings count would reset while the back stack itself is restored. To keep it, save it in a SavedStateHandle, which works with the same decorator.

Check it worked

BUILD SUCCESSFUL again, and the test report now lists RecipeViewModelTest with 3 passing tests next to KeysTest.

Step 5 · Show the back stack with NavDisplay

Now the screens and the activity. First the two recipe screens. They take plain values and lambdas, and know nothing about navigation:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/RecipeScreens.kt <<'EOF'
package com.example.pantry

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle

@Composable
fun RecipeListScreen(onOpenRecipe: (String) -> Unit) {
    LazyColumn(modifier = Modifier.fillMaxSize()) {
        item {
            Text(
                "Recipes",
                style = MaterialTheme.typography.headlineMedium,
                modifier = Modifier.padding(16.dp),
            )
        }
        items(recipes, key = { it.id }) { recipe ->
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onOpenRecipe(recipe.id) }
                    .padding(horizontal = 16.dp, vertical = 12.dp),
            ) {
                Text(recipe.name, style = MaterialTheme.typography.titleMedium)
                Text("${recipe.from} · ${recipe.minutes} min")
            }
            HorizontalDivider()
        }
    }
}

@Composable
fun RecipeDetailScreen(viewModel: RecipeViewModel, onBack: () -> Unit) {
    val recipe = viewModel.recipe
    val servings by viewModel.servings.collectAsStateWithLifecycle()

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        TextButton(onClick = onBack) { Text("Back to recipes") }
        if (recipe == null) {
            Text("This recipe is no longer available.", style = MaterialTheme.typography.titleMedium)
        } else {
            Text(recipe.name, style = MaterialTheme.typography.headlineMedium)
            Text("${recipe.from} · ${recipe.minutes} minutes")
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                OutlinedButton(onClick = viewModel::removeServing) { Text("Fewer") }
                Text("$servings servings", style = MaterialTheme.typography.titleMedium)
                OutlinedButton(onClick = viewModel::addServing) { Text("More") }
            }
        }
    }
}
EOF

Then the activity, with one back stack for now:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/MainActivity.kt <<'EOF'
package com.example.pantry

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator
import androidx.navigation3.ui.NavDisplay

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MaterialTheme {
                Surface(modifier = Modifier.fillMaxSize()) {
                    PantryApp()
                }
            }
        }
    }
}

@Composable
fun PantryApp() {
    // The back stack: a list you own, saved across rotation and process death.
    val backStack = rememberNavBackStack(RecipeList)

    NavDisplay(
        backStack = backStack,
        modifier = Modifier.safeDrawingPadding(),
        onBack = { backStack.removeLastOrNull() },
        entryDecorators = listOf(
            rememberSaveableStateHolderNavEntryDecorator<NavKey>(),
            rememberViewModelStoreNavEntryDecorator<NavKey>(),
        ),
        entryProvider = entryProvider<NavKey> {
            entry<RecipeList> {
                RecipeListScreen(onOpenRecipe = { id -> backStack.add(RecipeDetail(id)) })
            }
            entry<RecipeDetail> { key ->
                val recipeViewModel = viewModel { RecipeViewModel(key.recipeId) }
                RecipeDetailScreen(
                    viewModel = recipeViewModel,
                    onBack = { backStack.removeLastOrNull() },
                )
            }
        },
    )
}
EOF
gradle --console=plain :app:compileDebugKotlin

Read PantryApp from the top:

  • rememberNavBackStack(RecipeList) creates a NavBackStack, a list backed by Compose snapshot state, starting with one key. Adding or removing a key recomposes NavDisplay.
  • Opening a recipe is backStack.add(RecipeDetail(id)). The argument travels inside the key, so it is typed: you cannot forget it or pass a number where a string belongs.
  • entryProvider maps each key type to its content. entry<RecipeDetail> { key -> ... } hands you the key itself, so key.recipeId is the argument with no parsing.
  • onBack runs when the reader presses back or finishes a back swipe. Removing the last key is also what NavDisplay does if you leave onBack out; it is written here so you can see it. When only one key is left, NavDisplay stops handling back and Android closes the activity as usual.
  • The two decorators wrap every entry. The saveable state holder keeps each screen's rememberSaveable state (and the scroll position of the list) while it is under another screen. The ViewModel store decorator gives each entry its own ViewModelStore, so viewModel { ... } inside an entry is scoped to that entry and cleared when it is popped. It relies on the saveable state holder, so keep both, in that order.

Coming from Navigation Compose 2.x

If you maintain an app on Navigation Compose 2.x, the main differences are:

  • In 2.x, a NavController owns the back stack and you change it with navController.navigate(route) and popBackStack(). In Navigation 3 you change the list directly.
  • In 2.x, NavHost builds a graph of composable<Route> destinations and you read arguments with backStackEntry.toRoute<Route>(). In Navigation 3 there is no graph; entry<Key> { key -> } receives the key object.
  • In 2.x, every NavBackStackEntry is automatically a ViewModelStoreOwner. In Navigation 3 you opt in with the ViewModel store decorator.
  • In 2.x, separate tab histories come from saveState and restoreState on navigate. In Navigation 3 you keep one list per tab, which is the next step.

Both libraries can live in one app while you move screens across; Google's migration guide covers that.

Check it worked

gradle :app:compileDebugKotlin ends with BUILD SUCCESSFUL. If it reports Unresolved reference 'rememberViewModelStoreNavEntryDecorator', check that lifecycle-viewmodel-navigation3 is in app/build.gradle.kts.

Step 6 · Give each tab its own back stack

With bottom tabs, readers expect each tab to remember where they were. Open Githeri, switch to Profile, switch back, and Githeri should still be open. Back from the first Profile screen should return to Recipes, and back from the recipe list should leave the app, so readers always leave through the start tab.

You can model that with one back stack per tab plus a note of which tab is selected. NavDisplay is then shown the start tab's stack with the selected tab's stack on top of it. Write that logic as a class with no composables in it, so you can test it:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/TabNavigator.kt <<'EOF'
package com.example.pantry

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.navigation3.runtime.NavKey

enum class Tab(val root: NavKey, val label: String) {
    Recipes(RecipeList, "Recipes"),
    Profile(ProfileHome, "Profile"),
}

/**
 * One back stack per tab. The start tab's stack is always at the bottom of
 * what NavDisplay shows, so back from another tab's first screen returns to
 * the start tab, and back from the start tab's first screen leaves the app.
 */
class TabNavigator(
    private val stacks: Map<Tab, MutableList<NavKey>>,
    selectedTab: MutableState<Tab>,
    val startTab: Tab = Tab.Recipes,
) {
    init {
        require(stacks.keys == Tab.entries.toSet()) { "Every tab needs a back stack" }
    }

    var currentTab: Tab by selectedTab
        private set

    fun stackFor(tab: Tab): List<NavKey> = stacks.getValue(tab)

    /** The tabs whose screens are on the combined stack, bottom first. */
    val visibleTabs: List<Tab>
        get() = if (currentTab == startTab) listOf(startTab) else listOf(startTab, currentTab)

    /** Every key NavDisplay holds, bottom first. */
    val backStack: List<NavKey>
        get() = visibleTabs.flatMap { stackFor(it) }

    fun navigate(key: NavKey) {
        val stack = stacks.getValue(currentTab)
        if (stack.last() != key) stack.add(key) // ignore a double tap
    }

    /** Switches tab, or pops back to the tab's first screen if it is already selected. */
    fun selectTab(tab: Tab) {
        if (tab != currentTab) {
            currentTab = tab
            return
        }
        val stack = stacks.getValue(tab)
        while (stack.size > 1) stack.removeAt(stack.lastIndex)
    }

    /** Returns false when there is nowhere left to go back to in the app. */
    fun goBack(): Boolean {
        val stack = stacks.getValue(currentTab)
        return when {
            stack.size > 1 -> {
                stack.removeAt(stack.lastIndex)
                true
            }
            currentTab != startTab -> {
                currentTab = startTab
                true
            }
            else -> false
        }
    }
}
EOF

The tests describe the behaviour a reader of your app expects, one rule per test:

Bash
cd ~/pantry-nav-demo
cat > app/src/test/kotlin/com/example/pantry/TabNavigatorTest.kt <<'EOF'
package com.example.pantry

import androidx.compose.runtime.mutableStateOf
import androidx.navigation3.runtime.NavBackStack
import androidx.navigation3.runtime.NavKey
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class TabNavigatorTest {
    private val githeri = RecipeDetail("githeri")

    private fun newNavigator() = TabNavigator(
        stacks = mapOf(
            Tab.Recipes to NavBackStack<NavKey>(RecipeList),
            Tab.Profile to NavBackStack<NavKey>(ProfileHome),
        ),
        selectedTab = mutableStateOf(Tab.Recipes),
    )

    @Test
    fun startsOnTheRecipeList() {
        assertEquals(listOf<NavKey>(RecipeList), newNavigator().backStack)
    }

    @Test
    fun navigateAddsToTheCurrentTabAndIgnoresADoubleTap() {
        val navigator = newNavigator()
        navigator.navigate(githeri)
        navigator.navigate(githeri)

        assertEquals(listOf(RecipeList, githeri), navigator.backStack)
    }

    @Test
    fun eachTabKeepsItsOwnHistory() {
        val navigator = newNavigator()
        navigator.navigate(githeri)

        navigator.selectTab(Tab.Profile)
        navigator.navigate(EditName)
        assertEquals(listOf(RecipeList, githeri, ProfileHome, EditName), navigator.backStack)

        navigator.selectTab(Tab.Recipes)
        assertEquals(listOf(RecipeList, githeri), navigator.backStack)

        navigator.selectTab(Tab.Profile)
        assertEquals(listOf(ProfileHome, EditName), navigator.stackFor(Tab.Profile))
    }

    @Test
    fun backFromAnotherTabsFirstScreenReturnsToTheStartTab() {
        val navigator = newNavigator()
        navigator.selectTab(Tab.Profile)

        assertTrue(navigator.goBack())
        assertEquals(Tab.Recipes, navigator.currentTab)
        assertFalse(navigator.goBack()) // on the recipe list: let Android close the app
    }

    @Test
    fun tappingTheSelectedTabAgainPopsToItsFirstScreen() {
        val navigator = newNavigator()
        navigator.navigate(githeri)
        navigator.navigate(RecipeDetail("bobotie"))

        navigator.selectTab(Tab.Recipes)

        assertEquals(listOf<NavKey>(RecipeList), navigator.backStack)
    }
}
EOF

The tests pass real NavBackStack objects, the same type the app uses. Now the Profile screens:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/ProfileScreens.kt <<'EOF'
package com.example.pantry

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun ProfileScreen(displayName: String, onEditName: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Text("Profile", style = MaterialTheme.typography.headlineMedium)
        Text(if (displayName.isBlank()) "You have not set a display name." else "Display name: $displayName")
        Button(onClick = onEditName) { Text("Edit display name") }
    }
}

@Composable
fun EditNameScreen(currentName: String, onSave: (String) -> Unit, onLeave: () -> Unit) {
    var draft by rememberSaveable { mutableStateOf(currentName) }

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Text("Display name", style = MaterialTheme.typography.headlineMedium)
        OutlinedTextField(
            value = draft,
            onValueChange = { draft = it },
            label = { Text("Name") },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
        )
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Button(onClick = { onSave(draft.trim()) }) { Text("Save") }
            TextButton(onClick = onLeave) { Text("Cancel") }
        }
    }
}
EOF

Finally, replace MainActivity.kt so it uses a TabNavigator and a bottom navigation bar:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/MainActivity.kt <<'EOF'
package com.example.pantry

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberDecoratedNavEntries
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator
import androidx.navigation3.ui.NavDisplay

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MaterialTheme {
                PantryApp()
            }
        }
    }
}

private val Tab.icon: ImageVector
    get() = when (this) {
        Tab.Recipes -> Icons.Filled.Home
        Tab.Profile -> Icons.Filled.Person
    }

/** Creates the tab stacks and the selected tab, all saved across process death. */
@Composable
fun rememberTabNavigator(): TabNavigator {
    val recipesStack = rememberNavBackStack(Tab.Recipes.root)
    val profileStack = rememberNavBackStack(Tab.Profile.root)
    val selectedTab = rememberSaveable { mutableStateOf(Tab.Recipes) }
    return remember(recipesStack, profileStack, selectedTab) {
        TabNavigator(
            stacks = mapOf(Tab.Recipes to recipesStack, Tab.Profile to profileStack),
            selectedTab = selectedTab,
        )
    }
}

@Composable
fun PantryApp() {
    val navigator = rememberTabNavigator()
    var displayName by rememberSaveable { mutableStateOf("") }

    val provider = entryProvider<NavKey> {
        entry<RecipeList> {
            RecipeListScreen(onOpenRecipe = { id -> navigator.navigate(RecipeDetail(id)) })
        }
        entry<RecipeDetail> { key ->
            val recipeViewModel = viewModel { RecipeViewModel(key.recipeId) }
            RecipeDetailScreen(viewModel = recipeViewModel, onBack = { navigator.goBack() })
        }
        entry<ProfileHome> {
            ProfileScreen(displayName = displayName, onEditName = { navigator.navigate(EditName) })
        }
        entry<EditName> {
            EditNameScreen(
                currentName = displayName,
                onSave = { newName ->
                    displayName = newName
                    navigator.goBack()
                },
                onLeave = { navigator.goBack() },
            )
        }
    }

    // One set of decorators per tab. A tab that is off screen keeps its
    // screens' saved state and ViewModels until those screens are popped.
    val entriesByTab = Tab.entries.associateWith { tab ->
        rememberDecoratedNavEntries(
            backStack = navigator.stackFor(tab),
            entryDecorators = listOf(
                rememberSaveableStateHolderNavEntryDecorator<NavKey>(),
                rememberViewModelStoreNavEntryDecorator<NavKey>(),
            ),
            entryProvider = provider,
        )
    }

    Scaffold(
        bottomBar = {
            NavigationBar {
                Tab.entries.forEach { tab ->
                    NavigationBarItem(
                        selected = tab == navigator.currentTab,
                        onClick = { navigator.selectTab(tab) },
                        icon = { Icon(tab.icon, contentDescription = null) },
                        label = { Text(tab.label) },
                    )
                }
            }
        },
    ) { innerPadding ->
        NavDisplay(
            entries = navigator.visibleTabs.flatMap { entriesByTab.getValue(it) },
            modifier = Modifier.padding(innerPadding),
            onBack = { navigator.goBack() },
        )
    }
}
EOF
gradle --console=plain testDebugUnitTest

Two details in PantryApp matter. First, it uses the form of NavDisplay that takes entries instead of a backStack. If you passed the combined key list straight to NavDisplay, switching from Profile back to Recipes would remove the Profile keys from what NavDisplay holds, and their decorators would throw away the edit screen's draft and any ViewModels. rememberDecoratedNavEntries is called once per tab instead, so each tab's state lives as long as that tab's own stack. Second, the tab icons have contentDescription = null because the label next to each icon already names it; a screen reader would otherwise say "Recipes" twice.

Check it worked

The build ends with BUILD SUCCESSFUL, and the test report shows TabNavigatorTest with 5 passing tests, 11 in total. To see a rule catch a mistake, change listOf(startTab, currentTab) in visibleTabs to listOf(currentTab), run gradle testDebugUnitTest and watch eachTabKeepsItsOwnHistory fail, then change it back.

Step 7 · Handle the system back gesture

On Android, back is a system gesture or button, not only a control in your app. NavDisplay already handles it for you: a back swipe shows a predictive preview of the screen underneath, and lifting your finger calls your onBack. Predictive back is on by default for apps built against recent SDKs. You would only add android:enableOnBackInvokedCallback="false" to the manifest to opt out, and there is no reason to here.

Sometimes a screen must stop back for a moment. The edit screen should not silently throw away a half-typed name. BackHandler from activity-compose intercepts back while its enabled flag is true. Compose checks back callbacks from the innermost composable outwards, so a BackHandler inside an entry runs before NavDisplay's own handling.

Replace ProfileScreens.kt with a version that asks before discarding:

Bash
cd ~/pantry-nav-demo
cat > app/src/main/kotlin/com/example/pantry/ProfileScreens.kt <<'EOF'
package com.example.pantry

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun ProfileScreen(displayName: String, onEditName: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Text("Profile", style = MaterialTheme.typography.headlineMedium)
        Text(if (displayName.isBlank()) "You have not set a display name." else "Display name: $displayName")
        Button(onClick = onEditName) { Text("Edit display name") }
    }
}

@Composable
fun EditNameScreen(currentName: String, onSave: (String) -> Unit, onLeave: () -> Unit) {
    var draft by rememberSaveable { mutableStateOf(currentName) }
    var confirmDiscard by rememberSaveable { mutableStateOf(false) }
    val hasUnsavedChanges = draft.trim() != currentName

    // Only intercept back while there is something to lose. When this is
    // disabled, the swipe goes to NavDisplay and its predictive animation.
    BackHandler(enabled = hasUnsavedChanges) { confirmDiscard = true }

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Text("Display name", style = MaterialTheme.typography.headlineMedium)
        OutlinedTextField(
            value = draft,
            onValueChange = { draft = it },
            label = { Text("Name") },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
        )
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Button(onClick = { onSave(draft.trim()) }) { Text("Save") }
            TextButton(onClick = { if (hasUnsavedChanges) confirmDiscard = true else onLeave() }) {
                Text("Cancel")
            }
        }
    }

    if (confirmDiscard) {
        AlertDialog(
            onDismissRequest = { confirmDiscard = false },
            title = { Text("Discard your changes?") },
            text = { Text("Your new display name has not been saved.") },
            confirmButton = {
                TextButton(onClick = {
                    confirmDiscard = false
                    onLeave()
                }) { Text("Discard") }
            },
            dismissButton = {
                TextButton(onClick = { confirmDiscard = false }) { Text("Keep editing") }
            },
        )
    }
}
EOF
gradle --console=plain testDebugUnitTest

Keep enabled tied to real state, as here. A BackHandler that is always on swallows every back gesture, and while any handler is enabled the system cannot play the predictive preview for that swipe. Turned on only when there are unsaved changes, the edit screen behaves like every other screen until the reader types something.

For your own logging or analytics when a screen closes, do not add a back handler. Use the ViewModel's onCleared() or addCloseable, which run when the entry is popped by any route: a swipe, the back button, or navigator.goBack() from code.

Check it worked

The build ends with BUILD SUCCESSFUL and the same 11 tests pass, which shows the change compiled and nothing else moved. The dialog itself is checked on a phone in the next step.

Step 8 · Build the APK, try it on a phone and clean up

Build a debug APK:

Bash
cd ~/pantry-nav-demo
gradle --console=plain assembleDebug
ls -lh app/build/outputs/apk/debug/

To see it, connect an Android phone with USB debugging turned on (Android 7.0 or newer), or start an emulator from Android Studio, and install the APK. adb comes with the SDK's platform-tools package, which the first Compose tutorial installed:

Bash
adb devices
adb install -r ~/pantry-nav-demo/app/build/outputs/apk/debug/app-debug.apk

Open Pantry on the phone and walk through these checks:

  1. Tap Githeri, then More once. The screen says 5 servings.
  2. Tap Profile, then Recipes. You are back on Githeri, still at 5.
  3. Rotate the phone. Githeri and the count of 5 stay.
  4. Swipe back slowly from the edge of the screen. On Android 14 or newer you should see the recipe list behind the screen before you let go. Let go, then open Githeri again: the count is back to 4, because the old screen and its ViewModel were cleared.
  5. Tap Profile, then Edit display name, type a name and swipe back. The Discard your changes? dialog appears. Choose Keep editing, tap Save, and the Profile screen shows your name.
  6. On the Profile screen, press back. You land on the Recipes tab, still on Githeri. Press back to reach the recipe list, and back once more to close the app.

When you have finished, stop the Gradle daemon and delete the project. This removes only ~/pantry-nav-demo; the SDK and Gradle from the first Compose tutorial stay for the next one:

Bash
cd ~/pantry-nav-demo
gradle --stop
cd ~
rm -rf ~/pantry-nav-demo

Check it worked

ls -lh listed app-debug.apk before the clean-up, and each of the six checks on the phone behaved as described. After the clean-up, ls ~/pantry-nav-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.