我的问题与撰写导航和屏幕旋转有关。 屏幕旋转后,出于某种原因,据我所知,重新创建了可组合项并采用了 NavigationViewModel 的最新值,并将额外的可组合项/屏幕添加到后台堆栈中。 轮换后应该怎么做才能防止将新的可组合项添加到后台堆栈中?
@Composable
fun NavRoot() {
val navController = rememberNavController()
val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
}
navigationViewModel = hiltViewModel<NavigationViewmodel>(viewModelStoreOwner = viewModelStoreOwner)
NavigationHost(
navController = navController,
keys = navigationViewModel.keys,
navigationViewModel = navigationViewModel
)
}
@Composable
internal fun NavigationHost(
navController: NavHostController,
keys: List<NavigationKey>,
navigationViewModel: NavigationViewmodel,
) {
if (keys.isEmpty()) return
val startDestination = keys.first().key
val screenState by navigationViewModel.state.collectAsState(...)
when (val currentScreenState = screenState) {
...
navController.navigate(screenState.key)
}
NavHost(navController = navController, startDestination = startDestination) {
keys.forEach { screen ->
composable(screen.key) {
NavigationRouter(
screen = screen,
)
}
}
}
}
我试着玩记住导航控制器,不幸的是它没有帮助:(