Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose Navigation: Get route of current destination as string

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.

like image 962
Walter Berggren Avatar asked Mar 05 '21 13:03

Walter Berggren


2 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
}
like image 150
Mahmudul Hasan Shohag Avatar answered Oct 22 '22 09:10

Mahmudul Hasan Shohag


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

like image 25
Walter Berggren Avatar answered Oct 22 '22 07:10

Walter Berggren