简体   繁体   中英

How to acess NavHostController from nested composable Jetpack Compose

Assume that my application looks like this

@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("")
}

I want to access navController in nested composable to navigate but I dont want to pass navController from parent composable to child compsable as above

Is there anyway to access navController from anywhere inside NavHost without passing it through composable hierarchy

Edit: for now, I can use CompositionLocalProvider to access navController in nested compose as below

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")
    }) {
        ...
    }
}

With compose 1.0.0-beta04 and navigation 1.0.0-alpha10 as suggested by the official doc

  • Pass lambdas that should be triggered by the composable to navigate, rather than the NavController itself.
    @Composable
    fun ChildCompose(
        navigateTo: () -> Unit
    ) {
        //...
        navigateTo
    }

and to use it:

ChildCompose(navigateTo = {
    navController.navigate("...")
})

In this way ChildCompose composable works independently from Navigation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM