What is the ideal way to deal with arguments for a...
# compose-android
a
What is the ideal way to deal with arguments for a navigation graph? 🧵
I have a NavHost setup as
Copy code
NavHost(
    navController = navController,
    startDestination = BaseRouteGraphA,
    modifier = Modifier.fillMaxSize(),
) {

    graphA(
        navController = navController,
        onSomeThingSelected = { 
            navController.navigateToGraphB(it.myIdThatINeed)
        }
    )

    graphB( … )
    graphC( … )

}
And within graph B I am currently obtaining the
data
I need by
Copy code
fun NavController.navigateToGraphB(myIdThatINeed: Int) {
    navigate(route = BaseRouteGraphB(myIdThatINeed))
}

fun NavGraphBuilder.graphB( … ) {
    navigation<BaseRouteGraphB>(startDestination = ScreenB1) {
        composable<ScreenB1> { backStackEntry ->
            backStackEntry.arguments.getInt("myIdThatINeed")
            …
        }

        composable<ScreenB2> { … }
        composable<ScreenB3> { … }
    }
}
I was wondering if this approach is correct? Or if there is a better way to handle this
s
Yeah, using the type-safe navigation APIs, you should use this https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:navigation/navigation-common/src/main/java/androidx/navigation/NavBackStackEntry.kt;l=300?q=toRoute instead. It's a one liner and you get back the entire destination object. From there you can use the arguments in any way you wish, it's super simple.
a
I require the argument in
ScreenB1
. But if you notice, the argument was passed to the
BaseRouteGraphB
Yeah you can grab the NavBackstackEntry of your graph to do the .toRoute on.
Copy code
navController.getBackStackEntry<BaseRouteGraphB>()
a
Thanks, this indeed works.
Copy code
navController.getBackStackEntry<BaseRouteGraphB>().toRoute<BaseRouteGraphB>()
K 1