Lena
Lena

Reputation: 561

Missing road arguments value while using Navigation in Jetpack Compose

I created a road using Navigation (with Jetpack Compose) as so

                composable(CatLifeScreen.AddCatFormScreen.route + "?catId={catId}",
                    arguments = listOf(
                        navArgument(name = "catId") {
                            nullable = true
                        }
                    )) {
                    bottomBarState.value = false

                    val catId = it.arguments?.getInt("catId")

                    AddEditCatFormBody(
                        idOfCat = catId,
                        navController = navController,
                        addEditCatViewModel = addEditCatViewModel,
                    )

If I don't add any argument, the road works good

onClick = { navController.navigate(CatLifeScreen.AddCatFormScreen.route) }

If I define an argument it.arguments?.getInt("catId") is 0 when my passed argument is not 0.

IconButton(onClick = { navController.navigate(CatLifeScreen.AddCatFormScreen.route + "?catId=$idOfCat") } //idOfCat = 1

Does anyone have a lead to follow or something? I've been stuck for a long time now

Upvotes: 2

Views: 3062

Answers (2)

Lena
Lena

Reputation: 561

Finally found the answer. For anyone stuck like I was:

  1. Put the type of the data you want to receive

  2. Integer value can't be nullable (app will crash if you do).(see documentation https://developer.android.com/guide/navigation/navigation-pass-data#supported_argument_types ). In my case, I don't specify the type

  3. Fetch key in arguments using getString(key) and cast it to Int (only if you don't specify the type because you want it to be nullable. You probably could deal with it differently (like using -1 when you don't have a value to pass, instead of null)

    composable(CatLifeScreen.AddCatFormScreen.route + "?catId={catId}",
                arguments = listOf(
                    navArgument(name = "catId") {
                        nullable = true // I don't specify the type because Integer can't be nullable
                    }
                )) {
                bottomBarState.value = false
    
                val catId = it.arguments?.getString("catId")?.toInt() // Fetch key using getString() and cast it
    
                AddEditCatFormBody(
                    idOfCat = catId,
                    navController = navController,
                    addEditCatViewModel = addEditCatViewModel,
                )
            }
    

Upvotes: 2

Aytekin
Aytekin

Reputation: 11

try typing the argument type, like this;

           arguments = listOf(
                navArgument("catId") {
                    type = NavType.IntType
                    nullable = true
                }
           )

Upvotes: 0

Related Questions