I am writing an app that uses androidx.navigation to navigate between screens, and following this documentation:
https://developer.android.com/guide/navigation/design/kotlin-dsl
I'm struggling to understand how to access parameters at the destination.
My (simplified) screen route looks like:
@Serializable
data class TimerEntryRoute(
val operation: String,
...
)
I'm instantiating a route object in my NavHost with my parameter:
NavHost(
navController = navController,
startDestination = HomeRoute,
modifier = modifier
) {
composable<HomeRoute> {
HomeScreen(
navigateToTimerEntry = { navController.navigate(route = TimerEntryRoute(operation = "ENTER")) }
)
}
}
}
How can I then access that route object to receive my parameters at the destination? Do I have to use the back-stack toRoute function? Does the destination need to be passed the navController to do so? It seems there ought to be a cleaner way.
NavHost(
navController = navController,
startDestination = HomeRoute,
modifier = modifier
) {
composable<HomeRoute> {
HomeScreen(
navigateToTimerEntry = { navController.navigate(TimerEntryRoute(operation = "ENTER")) }
)
}
composable<TimerEntryRoute> { navBackStackEntry ->
// Retrieve the route parameters directly
val route = navBackStackEntry.toRoute<TimerEntryRoute>()
TimerEntryScreen(
operation = route.operation
)
}
}