kotlin 在jetpack compose导航中传递参数

pdtvr36n  于 2023-11-21  发布在  Kotlin
关注(0)|答案(1)|浏览(158)

我有一个重定向到食品的可点击行:

.clickable {
                // Navigate to FoodProductsScreen when clicked
                Log.d("Navigation", "Category ID: ${category.id}")

                navController.navigate("${NavGraph.FoodProducts}?categoryId=${category.id}")

            },`

字符串
当我在这里打印category.id时,它在控制台上记录2,但当我在NavHost中打印它时,它说0:

`        
composable(NavGraph.FoodProducts) { backStackEntry ->
           
            val categoryId = backStackEntry.arguments?.getInt("categoryId") ?: 2
            Log.d("Navigation", "Received Category ID: $categoryId")
            FoodProductsScreen(navController, categoryId)
        }`


食品屏幕:

`@Composable
fun FoodProductsScreen(navController: NavController, categoryId: Int) {
    val productsInCategory = products.filter { it.id == categoryId }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
    ) {
        Text(text = "${categoryId}")
    }
    LazyColumn {
        items(productsInCategory) { product ->
            FoodProductItem(product = product)
        }
    }
}`


我试过很多方法但都不管用...
我试着像这样从最后一个视图中检索参数:FoodProductsScreen(navController, backStackEntry.arguments?.getInt("categoryId") ?: 1),但它不起作用。

k2arahey

k2arahey1#

val categoryId = navController.currentBackStackEntry
    ?.savedStateHandle?.get<Int>("categoryId") ?: 2

字符串
你能试试这个吗?

相关问题