我正在使用 Jetpack Compose 和 Hilt 在嵌套导航设置中进行依赖注入。我需要在嵌套屏幕 (NestedHomeScreen) 及其父屏幕 (HomeScreen) 之间共享 ViewModel(具体来说,nested_home ViewModel)。这两个屏幕都是不同导航图的一部分,但我希望 HomeScreen 能够访问 NestedHomeScreen 中使用的相同 ViewModel 实例。
@Composable
fun MainNavGraph(navController: NavHostController) {
NavHost(navController = navController, startDestination = "home") {
composable("home") { HomeScreen(navController) }
composable("profile") { ProfileScreen(navController) }
composable("nested_container") { NestedContainerScreen(navController) }
}
}
@Composable
fun NestedContainerScreen(navController: NavHostController) {
// Create a nested NavController for the subgraph
val nestedNavController = rememberNavController()
// Nested NavHost as the subgraph
NavHost(navController = nestedNavController, startDestination = "nested_home") {
composable("nested_home") {
NestedHomeScreen(nestedNavController)
}
composable("nested_detail/{id}") { backStackEntry ->
val id = backStackEntry.arguments?.getString("id")
NestedDetailScreen(id = id)
}
}
}
val nestedHomeViewModel : HomeViewModel = hiltViewModel()
//need to access it in parent nav host home screen
笔记:
- 不要使用全局范围 viewmodel 与父级 navhost 进行共享
- 不要使用导航子图