Jetpack Compose Navigation: Get route of current destination as string

Viewed 7002

I'm using NavHost and a NavHostController to navigate in my Jetpack Compose application. To specify destinations, I use string-based routes:

NavHost(
    navController,
    startDestination = "FOO"
) {
    composable("FOO") {
        Foo()
    }
    composable("BAR") {
        Bar()
    }
}

I would like to retrieve the current route as a string (FOO or BAR) using the navController. The closest alternative I can find is navController.currentDestination.id that, however, returns a numeric ID, not the route as a string.

Is there any way to retrieve this value?

I'm using Jetpack Compose beta01 and Compose Navigation alpha08.

3 Answers

From androidx.navigation:navigation-compose version 2.4.0-alpha01, androidx.navigation.compose.KEY_ROUTE is replaced with navBackStackEntry?.destination?.route.

The KEY_ROUTE argument has been replaced with the route property on NavDestination, allowing you to call navBackStackEntry.destination.route directly.

Release Note for 2.4.0-alpha01

Example code:

val currentRoute = navController.currentBackStackEntry?.destination?.route

Or, if you need to observe the navigation:

val navBackStackEntry by navController.currentBackStackEntryAsState()

when (val currentRoute = navBackStackEntry?.destination?.route) {
    // do something with currentRoute
}

Resolved!

import androidx.navigation.compose.KEY_ROUTE

val currentRoute = navController.currentBackStackEntry?.arguments?.getString(KEY_ROUTE)

Not the cleanest solutions IMO, but it is used in the official Android documentation for navigating with compose: https://developer.android.com/jetpack/compose/navigation?hl=it

For those who have a problem with getting a route from NavDestination object, such as me. Check the class type. There are two classes of NavDestination.kt and NavDestination.java. Cast it to NavDestination.kt to be able to get the route value.

Related