Search code examples
androidandroid-jetpackandroid-jetpack-composeandroid-jetpack-navigation

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

Solution

  • 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