获取导航类型安全 Jetpack Compose 中的当前屏幕

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

屏幕

@Serializable
sealed class Screen {
    @Serializable
    data object Home : Screen()

    @Serializable
    data class Profile(val name: String) : Screen()
}

设置导航

@Composable
fun AppNavigation(
    modifier: Modifier = Modifier,
    startDestination: Screen = Screen.Home,
    navController: NavHostController = rememberNavController()
) {
    val currentNavBackStackEntry: NavBackStackEntry? by navController.currentBackStackEntryAsState()

    // Error
    val currentScreen: Screen = currentNavBackStackEntry?.toRoute<Screen>() ?: Screen.Home

    val navGraph = navController.createGraph(
        startDestination = startDestination,
    ) {
        composable<Screen.Home> {
            HomeScreen(onNavigateToProfile = { navController.navigate(it) })
        }
        composable<Screen.Profile> { navBackStackEntry ->
            val profile = navBackStackEntry.toRoute<Screen.Profile>()
            ProfileScreen(name = profile.name)
        }
    }

    NavHost(navController = navController, graph = navGraph, modifier = modifier)
}

我正在尝试从导航类型安全喷气背包组合获取当前屏幕。但

toRoute()
仅与导航图中的路线一起使用。

android android-jetpack-compose android-navigation android-jetpack-navigation
1个回答
0
投票

功能

hasRoute()
可以帮助您处理当前屏幕,如下所示:

val navBackStackEntry by navController.currentBackStackEntryAsState()

navBackStackEntry?.destination?.let { currentDestination ->
    shouldShowAppBar = !currentDestination.hasRoute(Settings::class)
}
© www.soinside.com 2019 - 2024. All rights reserved.