Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 104 ยท Navigation

Passing Arguments and Results

Pass typed arguments between Compose destinations, make some optional, return results to the previous screen, share ViewModels across destinations and know what never to pass.

A list screen opens a detail screen, and the detail screen needs to know which item to show. A "pick a date" screen closes, and the screen that opened it needs the date the user picked. Passing data between destinations sounds easy, but it is a common source of bugs: crashes after process death, stale data, and screens that cannot be tested. The rule that fixes most of them is short: pass identifiers, not objects, and let each screen load its own data.

This lesson covers typed route arguments, optional arguments, returning a result to the previous screen, sharing a ViewModel between destinations, and what you should never pass. The Navigation code is read-only (it needs the Android SDK); the TryIts are stand-ins that parse routes and decode arguments in plain Kotlin so you can see what the library does for you. The previous lesson, Navigation Compose Basics, introduced the controller and the host.

Typed arguments

With type-safe navigation, the arguments are the properties of the route class. You write them once and the library turns them into a route string, then back into an object:

Kotlin
// read-only example: needs the Android SDK and Navigation Compose 2.8+
@Serializable data class Detail(val id: Int)

// sending:
navController.navigate(Detail(id = 42))

// receiving, inside the NavHost:
composable<Detail> { entry ->
    val route: Detail = entry.toRoute()
    DetailScreen(id = route.id)
}

Under the hood the route becomes something like Detail/42 (the exact format is an implementation detail; do not build or parse it yourself). Supported types include primitives, strings, enums, lists of those and other @Serializable types. Because the property is an Int, a missing or non-numeric value fails fast instead of producing a wrong screen later.

The best place to read the argument is the ViewModel, not the composable. The ViewModel receives the arguments through its SavedStateHandle, and you can read them with the same route class:

Kotlin
// read-only example
class DetailViewModel(
    savedStateHandle: SavedStateHandle,
    private val repository: NoteRepository,
) : ViewModel() {
    private val route = savedStateHandle.toRoute<Detail>()
    val note: StateFlow<Note?> = repository.observe(route.id)
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
}

The screen then needs no argument at all: it asks the ViewModel for state. You will build these in ViewModel.

Optional arguments and defaults

An argument is optional when it has a default value in the route class (or is nullable with a default):

Kotlin
// read-only example
@Serializable data class Search(val query: String = "", val onlyFavorites: Boolean = false)

navController.navigate(Search())                     // uses defaults
navController.navigate(Search(query = "kotlin"))     // overrides one

Optional arguments become query parameters of the route, such as ?query=kotlin. Keep them for things like filters and initial tabs; required identity (which note to open) should be a normal property without a default.

The first stand-in is a tiny route parser with the same idea: a template with required parts and optional ?name=value parts, decoded to typed values. It makes it clear why the types matter.

Kotlin Parsing and decoding route arguments (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.

The two failing routes show the point of typed arguments: a bad value is reported where it enters, not three screens later.

What not to pass

Arguments are stored in a Bundle and restored after process death, so they have to be small and serializable. As a rule:

  • Pass: ids, keys, short strings, small enums, simple flags.
  • Do not pass: large objects, lists of records, bitmaps, Context, ViewModels, lambdas, or anything that is live state. A big object can exceed the Bundle size limit (about 1 MB for all transactions in the process) and throws TransactionTooLargeException; a copy goes stale as soon as the original changes.

If the detail screen needs a note, pass its id and load it from the repository. That way the screen shows current data, survives process death and can be tested with a fake repository. Also avoid URLs in raw form: if a string argument can contain / or ?, make sure it is encoded (typed routes do this for you).

Returning a result to the previous screen

A screen that was opened to choose something needs to send the choice back. There are two common patterns.

1. Result through the back stack entry's SavedStateHandle. Before popping, the child puts the result in the previous entry's handle; the parent observes it:

Kotlin
// read-only example
// in the child (picker) screen:
navController.previousBackStackEntry
    ?.savedStateHandle
    ?.set("picked_date", pickedDate.toString())
navController.popBackStack()

// in the parent screen:
val handle = backStackEntry.savedStateHandle
val pickedDate by handle.getStateFlow<String?>("picked_date", null).collectAsStateWithLifecycle()

The value must be something a Bundle can hold, and the parent should clear it after use (handle.remove("picked_date")) so it is not delivered again.

2. A shared state holder. If both screens use the same ViewModel (next section), the child calls viewModel.onDateSelected(date) and simply pops. The parent reads the state from the same ViewModel. This is easier to test and avoids string keys, but only works when the two screens share a scope.

The second stand-in implements pattern 1: a back stack where each entry owns a small key-value handle. The child writes into the previous entry and pops; the parent reads and clears the value.

Kotlin Returning a result through the previous entry (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.

Sharing a ViewModel between destinations

By default, viewModel() inside a destination creates a ViewModel scoped to that back stack entry: it lives while the entry is on the stack and is cleared when the entry is popped. To share one instance between several screens (for example the steps of a checkout), scope it to a parent: a nested graph or the host activity. In Navigation Compose you take the ViewModelStoreOwner of the parent entry:

Kotlin
// read-only example
composable<CheckoutAddress> { entry ->
    val parentEntry = remember(entry) { navController.getBackStackEntry<CheckoutGraph>() }
    val checkoutViewModel: CheckoutViewModel = viewModel(parentEntry)
    AddressScreen(checkoutViewModel)
}

All screens in the CheckoutGraph get the same CheckoutViewModel, and it is cleared when the whole graph leaves the back stack. Nested graphs are explained in Bottom Navigation and Nested Graphs. Use shared ViewModels sparingly: they couple screens together, and a screen that is opened directly through a deep link may not find its parent entry.

flowchart TD
    G["Parent scope<br/>(nested graph entry)"] --> VM["CheckoutViewModel<br/>(one instance)"]
    A["Address screen<br/>(entry)"] --> VM
    P["Payment screen<br/>(entry)"] --> VM
    C["Confirm screen<br/>(entry)"] --> VM

Screens that read the parent's ViewModel share its state; it lives as long as the parent entry.

Common mistakes

  • Passing a whole object through the route. Pass the id and load the data.
  • Reading arguments in the composable and loading data there, which repeats the load on recomposition. Use the ViewModel and SavedStateHandle.
  • Returning results with a global variable or a singleton that survives forever.
  • Not consuming a result, so it triggers again after rotation or when returning later.
  • Sharing a ViewModel at activity scope for convenience, which keeps it alive for the whole session and leaks old state.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What should you pass to a detail destination to show a note?

    Ids are small and serializable, survive process death and let the screen show current data from the repository.
  2. 2. How do you make an argument optional with type-safe routes?

    A property with a default value is optional; it appears as a query parameter in the route when it differs from the default.
  3. 3. In the SavedStateHandle result pattern, whose handle does the child screen write to?

    The child sets the value on navController.previousBackStackEntry's savedStateHandle and pops; the parent then reads (and should clear) it.
  4. 4. What happens to a ViewModel created with viewModel() inside a destination by default?

    The default scope is the entry. To share, you pass a parent entry (a nested graph) as the owner.
  5. 5. Why is passing large objects through a route a problem?

    Bundles are limited in size and meant for small data; large payloads can throw TransactionTooLargeException, and a copy does not update when the source does.

Summary

  • Typed routes make the properties of a @Serializable class the arguments; read them with toRoute() or through the ViewModel's SavedStateHandle.
  • Default values make arguments optional; keep required identity as plain properties.
  • Pass ids and small values, never large objects, contexts or lambdas.
  • Return results by writing into the previous entry's SavedStateHandle (and consuming it), or through a shared state holder.
  • ViewModels are scoped to their back stack entry; share one by scoping it to a parent graph, sparingly.
  • The Navigation code is read-only here; the TryIts model route parsing and the result handle.

Next: Back Stack, Launch Modes and Deep Links