从视图模型控制导航

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

我的 NavHost 和所有导航逻辑都在 jetpack 中。 我想知道,当我的视图模型初始化时,有没有办法导航(使用 navController)到某个页面?

如果不可能,有什么解决方法吗?

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

像这样构建流程

这是您的可组合项

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) }
}
© www.soinside.com 2019 - 2024. All rights reserved.