Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The Purpose of Navigation with Arguments

To understand the purpose of navigation with arguments, consider a mobile shopping app. You’re browsing shoes and find a pair you like. Tapping the shoe image takes you to the product details screen. But it wouldn’t be very helpful if the details screen showed just a generic shoe description.

Defining Navigation Arguments

Jetpack Compose navigation provides support for passing arguments between composable destinations of a navigation graph. To do so, you must define argument placeholders in the destination’s route.

NavHost(startDestination = "product-list-page") {
  composable("product-details-page/{productId}") { ... }
}

NavHost(startDestination = "product-list-page") {
  composable(
    "product-details-page/{productId}",
    arguments = listOf(navArgument("productId") { type = NavType.StringType })
  ) { ... }
}

Accessing Navigation Arguments

So far, you’ve learned how to define a navigation argument. Now, it’s time to understand how to extract and access an argument.

composable("product-details-page/{productId}") { backStackEntry ->
  ProductDetailsScreen(navController, backStackEntry.arguments?.getString("productId"))
}

Passing Navigation Arguments

To pass an argument to the destination, you must add it to the route when calling the navigate() function as follows:

navController.navigate("product-details-page/shoes-1629")

Handling Complex Data When Navigating

It’s strongly recommended not to pass large or complex data as navigation arguments but instead to pass minimum required data, which the destination can use to get access to required large or complex data, ideally using a data layer.

Optional Arguments

Jetpack Compose also supports optional navigation arguments, which differ from required arguments in the following ways: — They’re included using the query parameter syntax — ?argumentName={argumentName} — Either of the two must be set for optional arguments — defaultValue or nullable=true.

composable(
  "product-list-page/saleDiscountEnabled={saleDiscountEnabled}",
  arguments = listOf(navArgument("saleDiscountEnabled") { defaultValue = false })
) { backStackEntry ->
  ProductListScreen(navController, backStackEntry.arguments?.getString("saleDiscountEnabled"))
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo