Reputation: 3425
How do I declare a navigation route with multiple navigation arguments? I've checked the documentation, and all of these articles (which seem to simply reiterate what the documentation says), and I could only find examples of routes with one argument.
Here's what I have:
composable(
route = "createExercise/{exerciseId}",
arguments = listOf(navArgument("exerciseId") { type = NavType.IntType })
) { backStackEntry ->
CreateExerciseScreen(
exerciseId = backStackEntry.arguments!!.getInt("exerciseId"),
)
}
Here's what I want:
composable(
route = "createExercise/{exerciseId},{workoutId}",
arguments = listOf(
navArgument("exerciseId") { type = NavType.IntType },
navArgument("workoutId") { type = NavType.IntType },
)
) { backStackEntry ->
CreateExerciseScreen(
exerciseId = backStackEntry.arguments!!.getInt("exerciseId"),
workoutId = backStackEntry.arguments!!.getInt("workoutId"),
)
}
I arbitrarily chose a comma-seperated syntax for the example above in place of the real syntax which I am looking for.
So, my question is: When declaring a navigation route, what's the correct syntax for multiple arguments? (And what about optional arguments?)
Upvotes: 35
Views: 19295
Reputation: 1962
Here is an elaborated code for passing multiple arguments
// Declaring multiple arguments placeholders
NavHost(navController, startDestination = "profile/{userId}/{username}/{address}") { // or startDestination = "home"
composable(
"profile/{userId}/{username}/{address}", // declaring placeholder in String route
arguments = listOf( // declaring argument type
navArgument("userId") { type = NavType.IntType },
navArgument("username") { type = NavType.StringType },
navArgument("address") { type = NavType.StringType }
)
) { backStackEntry ->
// Extracting exact values and passing it to Profile() screen
val userId = backStackEntry.arguments?.getInt("userId")
val username = backStackEntry.arguments?.getString("username")
val address = backStackEntry.arguments?.getString("address")
Profile(navController, userId, username, address)
}
}
To pass exact values while performing navigation use this code
navController.navigate("profile/24/sriyanksid/India")
// userId = 24, username = "sriyanksid", address = "India"
Upvotes: 12
Reputation: 199805
As per the docs:
You can think of it as an implicit deep link that leads to a specific destination.
So it follows the same conventions as any other implicit deep link and conventions of RESTful URLs on the web, which would generally use a /
to separate different arguments to form the path of the URL - this covers the required arguments:
createExercise/{exerciseId}/{workoutId}
As per the optional arguments documentation that path of required arguments can be followed by any number of optional arguments in the form of one or more query parameters:
createExercise/{exerciseId}/{workoutId}?setNumber={setNumber}&repNumber={repNumber}
Upvotes: 68