Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-navigation

Android Jetpack navigation optional argument is returning default value


I have a Project with 2 screens a Home Screen that displays a list of recipes and a detail screen that display the recipe with more detail that the user clicked on. The problem I am having is that the recipeID that I attach to the route of the DetailScreen is not returning in savedStateHandle, Instead it is using the default value which is 0.

Here is a link to my project on my github The problem can be found in App -> src -> main -> java/com/googleplaystore/spoonfed -> presentation -> navigation -> DetailNavGraph

This is the detailnavGraph it shows the navigation call where the recipeId is attached to the route and also the composable

This is my AppNavHost, on line 25 you can see that I use the navigateToDetail function and I pass the recipeId to it.

This the recipeItem composable that gets the recipeId from the state and sets it val recipeId, recipeId is then passed up through other composable until it reaches the AppNavHost

This is my viewmodel, here you can see the saveStateHandle value on line 35 and also my api call function that takes the recipeId on line 48

Hopefully these images help better understand my problem.


Solution

  • thank you for providing a detailed explanation. I have compiled your project and identified the issue. The problem lies in the parsing of your navigateToDetail query. It should read detail_screen?recipeId=3 instead of detail_screen?recipeId={3}.

    To resolve this issue, please remove the curly braces and update the line of code as follows:

    Replace:

    this.navigate("${Screens.DetailScreen.route}?recipeId={$recipeId}")
    

    With:

    this.navigate("${Screens.DetailScreen.route}?recipeId=$recipeId")