我有一个视图模型,其值由屏幕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如何拥有视图模型的修改数据?
1条答案
按热度按时间ev7lccsx1#
问题是ViewModel的新示例不能访问以前ViewModel的状态。你必须传递ViewModel变量而不是创建一个新的。
我通常不建议在
Navigation
上执行此操作,但您需要将vm
值从ScreenOne
作为参数传递给接收@Composable
、ScreenTwo
。您还需要更新Navigation
代码,以便它可以接受传入的参数并将其传递给ScreenTwo
。另一方面,您也可以将
ViewModel
从@Composables
中全部提升出来:对于记录,这两个都不是理想的选择。最好的选择是在其他地方处理数据,并有两个单独的ViewModel可以访问它。