I'm using the AnimatedNavHost component in my Jetpack Compose app to manage navigation between different composable routes. I have added multiple navigation blocks to the AnimatedNavHost, and I want to obtain the route (it came from) of a specific navigation block.

For example, I have the following NavHost set up in my app:

@OptIn(ExperimentalAnimationApi::class)
@Preview
@Composable
fun NavGraph() {

    val navControl = rememberAnimatedNavController()

    AnimatedNavHost(
        navController = navControl,
        startDestination = "home",
    ) {

        navigation(
            route = "home",
            startDestination = "site1home",
        ) {
            composable(
                route = "site1home",
            ) {
            }

            composable(
                route = "site2home",
            ) {
            }
        }
    }
}

How can I obtain the route of the HomeRoute? I want to be able to access the route of each individual navigation block.

Example

My current Destination is "site1home" (API call for this navController.currentDestination?.route) is there a way to obtain from which nested graph main route I came from (in this example the main route is "home") so I can display it like this.

enter image description here

I have tried to read the NavController Documentation without success.

TLDR: Is there a GetNestedGraphMainRouteOfCurrentDestination function :D

1

There are 1 best solutions below

0
On BEST ANSWER

You can use Navcontroller's backStackEntry to get the main route of the navigation. currentBackStackEntryAsState() gets the current navigation back stack entry as a MutableState. When the given navController changes the back stack due to a NavController.navigate or NavController.popBackStack this will trigger a recompose and return the top entry on the back stack. Below is the sample block for the same.

@Composable
fun Site1(navController: NavHostController) {
   val navBackStackEntry by navController.currentBackStackEntryAsState()
   val mainRoute = navBackStackEntry?.destination?.parent?.route
   Text(text = mainRoute)
}

The above code will show text as home