在提供的设置中,我在Jetpack Compose应用程序中在屏幕1和屏幕2之间导航时遇到了一个问题。下面是问题的详细信息:
在屏幕1上,我有一个TextField,它更新viewModel,并在screen1_1中显示更新后的viewModel.uiState.name,因为viewModel状态是作为参数传入的
screen1_1(
name = viewM.uiState.name
)
字符串
当我单击屏幕2按钮时,它导航到屏幕2并显示通过navController传递的正确名称。navigate(“screen 2/${viewM.uiState.name}”)
但是,当我单击从屏幕2导航到屏幕1时,screen1_1重置为空?
当我导航回屏幕1时,如何保持viewModel状态
NavHost(navController = navController, startDestination = "screen1") {
composable("screen1") { screen1(navController) }
composable("screen2/{name}") { backStackEntry ->
val name = backStackEntry.arguments?.getString("name") ?: ""
screen2(navController, name)
}
}
@Composable
fun screen1(navController: NavHostController) {
val viewM: MyView = viewModel()
Column {
TextField(value = viewM.uiState.name, onValueChange = { viewM.updateName(it) })
screen1_1(
name = viewM.uiState.name
)
Button(onClick = { navController.navigate("screen2/${viewM.uiState.name}") }) {
Text(text = "screen 2")
}
}
}
@Composable
fun screen1_1(name: String) { Text(text = "Hello1 $name!") }
@Composable
fun screen2(navController: NavHostController, name: String) {
Column {
Text(text = "Name: $name", style = MaterialTheme.typography.bodyLarge)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { navController.navigate("screen1") }) {
Text(text = "Navigate to Screen 1")
}
}
}
data class MyData(var name: String = "")
class MyView(private val state: SavedStateHandle) : ViewModel() {
@OptIn(SavedStateHandleSaveableApi::class)
var uiState by state.saveable {
mutableStateOf(MyData(""))
}
private set
fun updateName(name: String) {
this.uiState = uiState.copy(name = name)
}
}
型
1条答案
按热度按时间ijnw1ujt1#
当您在screen2中运行
navController.navigate("screen1")
时,您实际上并没有返回到screen1,而是启动了一个新的screen1,因此使用navController.navigateUp()
代替navController.navigate("screen1")