In Jetpack Compose Navigation, the navArgument function is used to define an argument that can be passed to a destination when navigating. The function takes two parameters: the name of the argument, and an optional block of configuration options.
The configuration options can be used to specify the type of the argument and provide default values or other settings. The type option is required to specify the data type of the argument. In the code you provided, the type is set to NavType.StringType, which means that the argument will be a string value.
To pass an argument to a destination, you can use the navigate function on the NavController object, like this:
navController.navigate("plantDetail/123")
In this example, the argument value "123" is passed as part of the destination URL.
When defining the destination in the navigation graph, you use the composable
function to associate the destination with a composable function. If the destination requires an argument, you can use the arguments
parameter of the composable
function to define the argument.
In the code you provided, the "plantDetail/{plantId}" destination specifies an argument with the key "plantId" and type NavType.StringType
. The "gallery/{plantName}" destination specifies an argument with the key "plantName" and type NavType.StringType
.
You can define multiple arguments for a single destination by passing a list of navArgument
objects to the arguments
parameter. For example:
composable(
"myDestination/{arg1}/{arg2}",
arguments = listOf(
navArgument("arg1") { type = NavType.StringType },
navArgument("arg2") { type = NavType.IntType; defaultValue = 42 }
)
) { /* composable function */ }
In this example, the destination has two arguments: "arg1" of type string and "arg2" of type int. The "arg2" argument has a default value of 42. The arguments can be accessed in the composable function using the NavBackStackEntry
object, which is passed as a parameter to the function.