代码示例:
创建 ViewModel: class MyViewModel : ViewModel() { var username: String by mutableStateOf("") }
在 Composable 中使用 ViewModel: @Composable fun Screen1(viewModel: MyViewModel = viewModel()) { val username = viewModel.username TextField( value = username, onValueChange = { viewModel.username = it }, label = { Text("Username") } ) }
注意:在 Composable 中调用 viewModel() 函数获取 ViewModel 实例。
代码示例:
在 Navigation Graph 中定义 destination:
通过 Composable 使用该数据: @Composable fun Screen1(navController: NavHostController) { val username by navController.currentBackStackEntry?.arguments?.getString("username") ?: "" TextField( value = username, onValueChange = { navController.currentBackStackEntry?.arguments?.putString("username", it) }, label = { Text("Username") } ) }
注意:我们可以通过 NavHostController 对象获取到一个包含 arguments 的 currentBackStackEntry 的实例,然后通过 getString() 和 putString() 方法来读取和写入数据。