我遇到了一个问题,我在每个屏幕上使用
ViewModels
来存储 inputs
和 variables
。实施 Jetpack Compose navigation
后,我注意到它在配置更改时返回到 startDestination
。这使得在屏幕上使用 ViewModel
似乎无效,因为我们无法在配置更改期间保留数据。有趣的是,当我尝试不使用 Jetpack Compose navigation
时,单个屏幕在配置更改后仍然存在。任何有关解决此问题的指导将不胜感激,因为我目前陷入这种情况。
I am not sure about your viewModel code implementation and NavHost code which would be helpful to solve exact issue, but you
can correlate with this code to keep your state persist while using the navigation using the viewModel.
class NavigationViewModel : ViewModel() {
// Add properties and methods to hold navigation state and other relevant data
}
Use viewModel() to access the ViewModel from your composable functions. Make sure to use the same instance of the ViewModel throughout your navigation graph
@Composable
fun ScreenA(navViewModel: NavigationViewModel = viewModel()) {
// Access and modify the navigation state in navViewModel
}
@Composable
fun ScreenB(navViewModel: NavigationViewModel = viewModel()) {
// Access and modify the navigation state in navViewModel
}
Utilize SavedStateHandle within your ViewModel to save and restore data across configuration changes.
class NavigationViewModel(private val savedStateHandle: SavedStateHandle)
: ViewModel() {
// Add properties and methods to hold navigation state and other relevant
data
// Example of saving and restoring state
var count: Int by savedStateHandle.delegate(defaultValue = 0)
}
class NavigationViewModel : ViewModel() {
// Example navigation state
private var currentScreen: String by mutableStateOf("ScreenA")
fun navigateTo(screen: String) {
currentScreen = screen
}
}
//Initialize your navigation graph with the custom ViewModel.
val navController = rememberNavController()
val navViewModel: NavigationViewModel = viewModel()
NavHost(navController, startDestination = "ScreenA") {
composable("ScreenA") {
ScreenA(navViewModel)
}
composable("ScreenB") {
ScreenB(navViewModel)
}
}