Search code examples
androidandroid-architecture-navigation

Accessing parameters passed via kotlin NavHost at the destination


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.


Solution

  •   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
    
                    )
                }
            }
    
    • Use navBackStackEntry.toRoute() to retrieve the route parameters.
    • You don't need to pass the navController to the destination screen unless you specifically need it for navigation actions.
    • The toRoute() function is provided by the navigation library and allows you to directly extract the route parameters.