Skip to content

Instantly share code, notes, and snippets.

@Ifeo-A
Created November 16, 2022 21:32
Show Gist options
  • Save Ifeo-A/0f2ad46ea1ffbf9042df7205d75e1b28 to your computer and use it in GitHub Desktop.
Save Ifeo-A/0f2ad46ea1ffbf9042df7205d75e1b28 to your computer and use it in GitHub Desktop.
Nav controller extension to pass objects to destinations
// Using the nav controller extension
@Composable
fun MainNavigation() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = Destinations.HOME) {
composable(route = Destinations.HOME) {
HomeScreen { recipe ->
navController.navigate(
route = Destinations.RECIPE_DETAIL,
// Pass in the object to the navcontroller argument
args = bundleOf(DestinationArguments.RECIPE to recipe)
)
}
}
composable(route = Destinations.RECIPE_DETAIL) {
// Get the object passed in to the nav controller
navController.currentBackStackEntry?.arguments?.apply {
val recipe = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
this.getParcelable(DestinationArguments.RECIPE, Recipe::class.java)
} else {
this.getParcelable(DestinationArguments.RECIPE) as Recipe?
}
recipe?.let {
RecipeDetailScreen(recipe = it)
}
}
}
}
}
/**
* Written by Valentin Yuryev from StackOverflow
* https://stackoverflow.com/a/68847035
*/
@SuppressLint("RestrictedApi")
fun NavController.navigate(
route: String,
args: Bundle,
navOptions: NavOptions? = null,
navigatorExtras: Navigator.Extras? = null
) {
val routeLink = NavDeepLinkRequest
.Builder
.fromUri(NavDestination.createRoute(route).toUri())
.build()
val deepLinkMatch = graph.matchDeepLink(routeLink)
if (deepLinkMatch != null) {
val destination = deepLinkMatch.destination
val id = destination.id
navigate(id, args, navOptions, navigatorExtras)
} else {
navigate(route, navOptions, navigatorExtras)
}
}
@Parcelize
data class Recipe(
val name: String,
val image: String,
val ingredients: List<String>,
val instructions: List<String>,
val servings: String,
val timeToPrepare: Time,
) : Parcelable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment