Home > Software engineering >  Jetpack Compose Optional Arguments: What's the string between the braces {}?
Jetpack Compose Optional Arguments: What's the string between the braces {}?

Time:07-05

When working with optional arguments in Compose: What's the value between the braces?

"item=" is the key. What is the purpose of the string within the braces?

composable("Details?item={item}",
        arguments = listOf(navArgument("item") {
            this.type = NavType.StringType
            defaultValue = "Item not available!"
        })) {

CodePudding user response:

You have it backwards - the name of the query parameter (the item= part) could be anything. It could be lorem_ipsum or foobar or any word - that word isn't used by Navigation at all for figuring out how to parse that argument. The only thing that matters is the structure of your route pattern - that query parameter syntax is how you mark a parameter as an optional argument. Just like a web URL, you could navigate to Details as well as Details?item=cat - both would match your route. A required parameter would be part of the path (i.e., Details/{item}).

As explained in the Navigate with arguments guide:

Navigation compose also supports passing arguments between composable destinations. In order to do this, you need to add argument placeholders to your route, similar to how you add arguments to a deep link when using the base navigation library

That {item} is the placeholder that indicates that whatever string is in the place of the {item} should be parsed and put as an argument with the name item. This is how you can call navBackStackEntry.arguments?.getString("item") and get that parsed value out of the arguments of the destination.

  • Related