英文:
Android Jetpack navigation optional argument is returning default value
问题
我有一个项目有两个屏幕,一个主屏幕显示菜谱列表,另一个详细屏幕显示用户点击的菜谱的详细信息。我遇到的问题是,我附加到DetailScreen路由的recipeID没有在savedStateHandle中返回,而是使用默认值0。
这是我的GitHub项目链接
问题可以在App -> src -> main -> java/com/googleplaystore/spoonfed -> presentation -> navigation -> DetailNavGraph中找到
这是detailnavGraph,显示了将recipeId附加到路由的导航调用和可组合部分
这是我的AppNavHost,在第25行你可以看到我使用navigateToDetail函数,并将recipeId传递给它
这是recipeItem的可组合部分,它从状态中获取recipeId并将其设置为val recipeId,然后通过其他可组合部分传递,直到它到达AppNavHost
这是我的ViewModel,在这里你可以看到第35行的saveStateHandle值,以及在第48行接受recipeId的api调用函数
希望这些图片能更好地帮助理解我的问题。
英文:
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
Hopefully these images help better understand my problem.
答案1
得分: 0
感谢您提供详细的解释。我已经编译了您的项目并且找到了问题所在。问题出在解析您的 navigateToDetail
查询上。它应该是 detail_screen?recipeId=3
而不是 detail_screen?recipeId={3}
。
为了解决这个问题,请去掉花括号,并且按照以下方式更新代码行:
替换:
this.navigate("${Screens.DetailScreen.route}?recipeId={$recipeId}")
为:
this.navigate("${Screens.DetailScreen.route}?recipeId=$recipeId")
英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论