屏幕
@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()
仅与导航图中的路线一起使用。
功能
hasRoute()
可以帮助您处理当前屏幕,如下所示:
val navBackStackEntry by navController.currentBackStackEntryAsState()
navBackStackEntry?.destination?.let { currentDestination ->
shouldShowAppBar = !currentDestination.hasRoute(Settings::class)
}