Code
Create PicaNavHost.kt — the graph
Now the graph. navigation/PicaNavHost.kt (in the code column).
rememberNavBackStack(Screen.Menu)— a stack starting at the menu.NavDisplay(backStack, entryProvider { ... })— draws the top of the stack.entry<Screen.Menu> { MenuScreen(...) }— maps theMenukey to the menu screen.onCartClick = { backStack.add(Screen.Cart) }— the menu's "cart" button pushesCartonto the stack.viewModel()creates oneCartViewModel, shared by the menu and the cart. No Koin yet — we introduce it in lesson 6; for nowviewModel()is enough (the ViewModel has no dependencies).
You need a small MenuScreen change — so it can navigate to the cart and add pizzas to it. Add the params and buttons:
@Composable
fun MenuScreen(
cartViewModel: CartViewModel,
onCartClick: () -> Unit,
items: List<MenuItem> = sampleMenu // the real list arrives in lesson 5
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Pica Menu") },
actions = { IconButton(onClick = onCartClick) {
Icon(Icons.Default.ShoppingCart, contentDescription = "Cart")
} }
)
}
) { padding -> /* … LazyColumn of cards … */
// in a card:
Button(onClick = { cartViewModel.onEvent(CartEvent.AddItem(item)) }) { Text("Add to cart") }
}
}
Finally — MainActivity from lesson 1: replace Greeting("Pica") with PicaNavHost(). Navigation is finally on.
Verify. Run it. You should:
1. MENU opens with pizzas + a cart icon in the top bar.
2. Tap "Add to cart" on Margherita → the cart shows it has something.
3. Tap the cart icon → CART opens with Margherita and total €8.50.
4. Press the phone's Back → back to the MENU.
Two screens, one flow.
Gotcha (Nav3 alpha). Because Navigation 3 is still alpha, expect small API mismatches:
NavDisplay,entryProvider,rememberNavBackStackmay live in a different package or under a different name in your version. If an import is red — don't guess, open the official Nav3 docs and check the exact name for your library version. This is normal with alpha libraries; the course code targetsnavigation3 1.1.4.