我有一个视图模型,其值由Screen1更新,但我希望屏幕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.
}
screenttwo如何拥有视图模型的修改数据?
问题是ViewModel的新实例不能访问以前的ViewModel的状态。您必须传递ViewModel变量,而不是创建一个新变量。
我通常不建议在Navigation
上这样做,但您需要将vm
值从ScreenOne
作为参数传递给接收@Composable
,ScreenTwo
。您还需要更新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可以访问它。