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.
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.
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
}
// Or,
LaunchedEffect(navBackStackEntry) {
val currentRoue = navBackStackEntry?.destination?.route
// do something with currentRoute
}
Or, observe using addOnDestinationChangedListener
:
navController.addOnDestinationChangedListener { controller, destination, arguments ->
// ...
}