Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. The Navigation library also provides a specific artifact to enable consistent and idiomatic navigation within screens built with Jetpack Compose.
When using navigation with jetpack compose, we define a nav host using the
NavHost composable, which provides a lambda function in which we can add a destination to the
Suppose that we wish to navigate between
ScreenB It’ll look like
By default, all arguments are parsed as strings
As the documentation said, navigation compose also supports passing arguments between composable destinations and by default, all arguments are parsed as strings.
You should extract the
NavArguments from the
NavBackStackEntry that is available in the lambda of the
To pass the argument to the destination, you need to add the value to the route in place of the placeholder in the call to navigate:
Creating a custom data type
The above way works in most cases. You just have to pass the id and then fetch the additional information from the database. But sometimes you just want to pass your data to another screen without doing an additional request.
Jetpack navigation component allow us to create custom NavType.
NavType denotes the type that can be used in a
Suppose that we want to pass a custom Post data type to ScreenB
We can create a “Post NavType”, Post must first be parcelable.
Then we can create PostType class
The PostType extend from NavType which has the Post data class as type parameter, I also use Gson in order to deserialize the Post from argument which w’ll be a json, but you can use the convertor that you prefer.
we must update the NavGraph in order to be able to retrieve the post
Now the question is about how to pass the post as parameter. First we must serialize and then encode it to uri.
This works well, but we can create a function in which we can encapsulate the serialization line, in my case a overloaded the
Now we can just use string interpolation
Despite the fact that the Jetpack Compose team doesn’t recommend passing Parcelable in the navigation composable routes, you may sometimes still need to pass a custom data type as parameter and I hope this blog post can help you…
This article was originally published on proandroiddev.com on April 07, 2022