简体   繁体   中英

How to navigate up from one NavHost to another in Jetpack Compose?

So I have root navigation graph that contains HomeScreen, which is nothing but a Navigation graph itself, with it's own NavHostController, because in HomeScreen I use bottom navigation bar.

This is RootNavGraph

@Composable
fun RootNavigationGraph (navController: NavHostController){
    NavHost(
        navController = navController,
        route = "root_graph",
        startDestination = Screen.Welcome.route
    ){

        composable(route = Screen.Welcome.route){
            WelcomeScreen(navController = navController)
        }

        composable(route = Screen.Start.route){
            StartScreen(navController = navController)
        }

        composable(
            route = Screen.Home.route
        ){
            HomeScreen()
        }

    }
}

here HomeScreen() is with bottom navigation:

@Composable
fun HomeScreen(navController : NavHostController = rememberNavController()){
    Scaffold(
        bottomBar = { TabBar(navHostController = navController) }
    ) { innerPadding  ->

        Box(
            modifier = Modifier.padding(innerPadding)
        ){
            HomeNavGraph(navController = navController)
        }
    }
}

as you can see it contains another NavHostController, because HomeNavGraph contains NavHost.

now inside this NavHost I have composable from which at certain point I want to navigate up to the RootNavigationGraph's Screen.start.route but can't find a solution to this probelm.

If I try to simply go up (I want to pop everything up from backstack also):

navController.navigate(Screen.Start.route)
{
   popUpTo(Screen.Start.route){
      inclusive = true
   }
}

it gives me error:

java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/root_graph } cannot be found in the navigation graph NavGraph(0x442b361f) route=home_screen startDestination={Destination(0x78cb4ec6) route=MAIN}

You have two different navControllers within the app. One in the RootNavigationGraph and one within the HomeScreen. HomeScreen has the navController defined as a parameter, but isn't passed.

Because you don't pass a navController to the HomeScreen, a new navController is created. This one doesn't have any knowledge of the routes defined in the RootNavigationGraph

You should pass the navController from RootNavigationGraph to the HomeScreen. That would probably fix the issue.

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