我有一个多后堆栈导航图,其中底部导航的每个起始节点都是顶层。
如何检查我当前是否位于顶级目的地,以便调整 UI 元素的显示?
以下代码示例无法解决问题:
val isTopLevel = navController.previousBackStackEntry == null
在顶级目的地之间,我按如下方式导航:
navController.navigate(destination.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
inclusive = true
}
launchSingleTop = true
restoreState = true
}
一个技巧是定义您的顶级目的地。例如:
@Composable
fun MyScreen(navController: NavController) {
val topLevelDestinations = listOf("home", "profile", "settings") // Replace with your actual route names
val currentDestination = navController.currentBackStackEntryAsState().value?.destination
val isTopLevelDestination = currentDestination?.route in topLevelDestinations
// Use isTopLevelDestination to modify your UI
if (isTopLevelDestination) {
// Your UI for top-level destination
Text(text = "You are in a top-level destination")
} else {
// Your UI for non-top-level destination
Text(text = "You are in a nested destination")
}
}