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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With