jetpack compose 中的条件导航起始目的地

Ann*_*non 3 android kotlin android-jetpack-compose

navigation-compose我在 jetpack compose 中与底部栏一起使用。我想为不同类型的用户显示不同的底部栏。为此,我需要startDestination在 中设置条件NavHost。我怎么做?

我在下面尝试过,但它发生了变化startDestination,但没有反映在用户界面中。

val user by remember { mutableStateOf(viewModel.user) }.collectAsState()
var startDestination = Screens.UserType1.route

LaunchedEffect(user) {
    startDestination = if (loggedInUser?.userType == UserType.Seller) Screens.SellerHome.route else Screens.BuyerHome.route
}
Run Code Online (Sandbox Code Playgroud)

虽然下面的代码抛出 java.util.NoSuchElementException: List contains no element matching the predicate.

when (user?.userType) {
    UserType.Seller -> {
        startDestination = Screens.SellerHome.route
    }

    UserType.Buyer -> {
        startDestination = Screens.BuyerHome.route
    }

    else -> {}
}
Run Code Online (Sandbox Code Playgroud)

我的导航主机

NavHost(
        modifier = modifier,
        navController = navController,
        startDestination = startDestination
) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

小智 7

改变这个

var startDestination = Screens.UserType1.route
Run Code Online (Sandbox Code Playgroud)

对此

var startDestination by remember { mutableStateOf(Screens.UserType1.route) } 
Run Code Online (Sandbox Code Playgroud)

  • 我玩过“remember”和“mutableStateOf()”数百次,但仍然忘记了这个简单的事情。谢谢。我喜欢堆栈溢出。 (2认同)