类型安全导航 Jetpack Compose 中出现意外的空值

问题描述 投票:0回答:1

这是我的导航图的片段:

MyApp.kt

navigation<MainApp>(startDestination = Home) {
                composable<Home> {
                    atHomeScreen = true
                    HomeScreen(
                        onClick = { categoryId ->
                            navController.navigate(Items(categoryId = categoryId))
                        }
                    )
                }

                composable<Items>(
                ) { backStackEntry ->
                    val categoryId: String = backStackEntry.toRoute()
                    atHomeScreen = false
                    ItemsScreen(categoryId)
                }
                   //...
}

如您所见,我传递了从

String
Home
的非空
Items
类别 ID。但仍然以某种方式为
categoryId
分配了一个空值。请帮我调试这个。

注:

HomeScreen.kt

@Composable
fun HomeScreen(
    onClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val viewModel: HomeViewModel = hiltViewModel()
    val categories by viewModel.itemCategories.collectAsStateWithLifecycle()

    Column(
        modifier = modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState()),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        categories.forEach { category ->
            DataCard(
                title = category.title,
                imageUrl = category.imageUrl,
                onCardClick = {
                    onClick(category._id.toHexString())
                }
            )
        }
    }
}

路线.kt

@Serializable
data class Items(val categoryId: String)    //definition of Items route
android navigation android-jetpack-compose
1个回答
0
投票

在接收部分应该是

          composable<Items>(
            ) { backStackEntry ->
                val categoryId: Items = backStackEntry.toRoute()
                atHomeScreen = false
                ItemsScreen(Items.categoryId)
            }
© www.soinside.com 2019 - 2024. All rights reserved.