kotlin 在屏幕导航之间维护视图模型中的值

k5hmc34c  于 2023-04-07  发布在  Kotlin
关注(0)|答案(1)|浏览(92)

我有一个视图模型,其值由屏幕1更新,但我希望屏幕2获得这些值:

@HiltViewModel
class VM @Inject constructor(): ViewModel() {

var appState :Boolean by mutableStateOf(false)
}

@Destination
@Composable
fun ScreenOne(nav: DestinationsNavigator, vm: VM = hiltViewModel()){
   //update the vm here.
   vm.appState.value = true;
   nav.navigate(ScreenTwoDestination());
}

@Destination
@Composable
fun ScreenTwo(vm: VM = hiltViewModel()){
    Log.i(vm.appState); // this never changes and is also false even though the vm was correctly updated before the navigation happened.
}

ScreenTwo如何拥有视图模型的修改数据?

ev7lccsx

ev7lccsx1#

问题是ViewModel的新示例不能访问以前ViewModel的状态。你必须传递ViewModel变量而不是创建一个新的。
我通常不建议在Navigation上执行此操作,但您需要将vm值从ScreenOne作为参数传递给接收@ComposableScreenTwo。您还需要更新Navigation代码,以便它可以接受传入的参数并将其传递给ScreenTwo

@HiltViewModel
class VM @Inject constructor(): ViewModel() {

var appState :Boolean by mutableStateOf(false)
}

@Destination
@Composable
fun ScreenOne(nav: DestinationsNavigator, vm: VM = hiltViewModel()){
   vm.appState.value = true;
   // notice how I added the "vm" variable as an argument
   // This allows us to pass the existing instance of the ViewModel
   nav.navigate(ScreenTwoDestination(vm));
}

@Destination
@Composable
fun ScreenTwo(vm: VM = hiltViewModel()){
    Log.i(vm.appState);

另一方面,您也可以将ViewModel@Composables中全部提升出来:

@HiltViewModel
class VM @Inject constructor(): ViewModel() {

var appState :Boolean by mutableStateOf(false)
}
val vm = hiltViewModel()

@Destination
@Composable
fun ScreenOne(nav: DestinationsNavigator){
   vm.appState.value = true;
   nav.navigate(ScreenTwoDestination());
}

@Destination
@Composable
fun ScreenTwo(){
    Log.i(vm.appState);

对于记录,这两个都不是理想的选择。最好的选择是在其他地方处理数据,并有两个单独的ViewModel可以访问它。

相关问题