假设我的应用程序看起来像这样
@Composable
fun AppNavigation() {
val navController = rememberNavController()
NavHost(navController, startDestination = Route.Home.route) {
/// other composes
composable("Home") { HomeCompose(navController) }
}
}
@Composable
fun HomeCompose(navController: NavHostController) {
ChildCompose(navController)
}
@Composable
fun ChildCompose(navController: NavHostController) {
navController.navigate("")
}
我想在嵌套可组合中访问 navController 以进行导航 但我不想将 navController 从父可组合传递给子可组合
无论如何都可以从 NavHost 内部的任何地方访问 navController 而无需通过可组合的层次结构
编辑:现在,我可以使用 CompositionLocalProvider 在嵌套组合中访问 navController ,如下所示
val AppNavController = compositionLocalOf<NavHostController>() { error("NavHostController error") }
@Composable
fun AppNavigation() {
val navController = rememberNavController()
CompositionLocalProvider(
AppNavController provides navController
) {
NavHost(navController, startDestination = Route.Home.route) {
/// other composes
composable("Home") { HomeCompose() }
}
}
}
@Composable
fun HomeCompose() {
ChildCompose()
}
@Composable
fun ChildCompose(navController: NavHostController) {
val navController = AppNavController.current
Column(modifier = Modifier.clickable {
navController.navigate("Content")
}) {
...
}
}
答案 0 :(得分:1)
使用 official doc 建议的撰写 1.0.0-beta04
和导航 1.0.0-alpha10
NavController
本身。 @Composable
fun ChildCompose(
navigateTo: () -> Unit
) {
//...
navigateTo
}
并使用它:
ChildCompose(navigateTo = {
navController.navigate("...")
})
通过这种方式,ChildCompose
可组合独立于 Navigation