我的 NavHost 和所有导航逻辑都在 jetpack 中。 我想知道,当我的视图模型初始化时,有没有办法导航(使用 navController)到某个页面?
如果不可能,有什么解决方法吗?
像这样构建流程
这是您的可组合项
val viewModel: AAAViewModel = viewModel()
val state by viewModel.screenState.collectAsState()
LaunchedEffect(key1 = state.isComplete) {
if (state.isComplete) {
//navigate to your required screen but first reset variable so when you came back it doesnt get stuck in loop
viewModel.clearCompleteVariable()
navController.navigate(PinScreenDestination)
}
}
您的视图模型
//declare it outside viewmodel
data class AAAScreenState(
val isComplete: Boolean = false,
)
//inside viewmodel
var screenState = MutableStateFlow(
AAAScreenState()
)
fun testFunc(){
screenState.update { a-> a.copy(isComplete=true) }
}
fun clearCompleteVariable(){
screenState.update { a-> a.copy(isComplete=false) }
}