How to pass object in navigation in jetpack compose?

Viewed 9431

From the documentation, I can pass string, integer etc. But how can I pass objects on navigation?

Note: If I set the argument type parcelable then the app crashes with java.lang.UnsupportedOperationException: Parcelables don't support default values..

composable(
    "vendor/details/{vendor}",
        arguments = listOf(navArgument("vendor") {
            type = NavType.ParcelableType(Vendor::class.java)
        })
) {
// ...
}
3 Answers

The following workarounds based on navigation-compose version 2.4.0-alpha05.


I found 2 workarounds for passing objects.

1. Convert the object into JSON string:

Here we can pass the objects using the JSON string representation of the object.

Example code:

val ROUTE_USER_DETAILS = "user-details/user={user}"


// Pass data (I am using Moshi here)
val user = User(id = 1, name = "John Doe") // User is a data class.

val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(User::class.java).lenient()
val userJson = jsonAdapter.toJson(user)

navController.navigate(
    ROUTE_USER_DETAILS.replace("{user}", userJson)
)


// Receive Data
NavHost {
    composable(ROUTE_USER_DETAILS) { backStackEntry ->
        val userJson =  backStackEntry.arguments?.getString("user")
        val moshi = Moshi.Builder().build()
        val jsonAdapter = moshi.adapter(User::class.java).lenient()
        val userObject = jsonAdapter.fromJson(userJson)

        UserDetailsView(userObject) // Here UserDetailsView is a composable.
    }
}


// Composable function/view
@Composable
fun UserDetailsView(
    user: User
){
    // ...
}

2. Passing the object using NavBackStackEntry:

Here we can pass data using navController.currentBackStackEntry and receive data using navController.previousBackStackEntry.

Example code:

val ROUTE_USER_DETAILS = "user-details/{user}"


// Pass data
val user = User(id = 1, name = "John Doe") // User is a parcelable data class.

navController.currentBackStackEntry?.arguments?.putParcelable("user", user)
navController.navigate(ROUTE_USER_DETAILS)


// Receive data
NavHost {
    composable(ROUTE_USER_DETAILS) { backStackEntry ->
        val userObject = navController.previousBackStackEntry?.arguments?.getParcelable<User>("user")
        
        UserDetailsView(userObject) // Here UserDetailsView is a composable.
    }
}


// Composable function/view
@Composable
fun UserDetailsView(
    user: User
){
    // ...
}

Important Note: The 2nd solution will not work if we pop up back stacks on navigate.

Parcelables currently don't support default values so you need to pass your object as String value. Yes it is a work around.. So instead of passing object itself as Parcelize object we can turn that object into JSON (String) and pass it through navigation and then parse that JSON back to Object at destination. You can use GSON for object to json string conversion...

Json To Object

fun <A> String.fromJson(type: Class<A>): A {
    return Gson().fromJson(this, type)
}

Object To Json String

fun <A> A.toJson(): String? {
    return Gson().toJson(this)
}

User NavType.StringType instead of NavType.ParcelableType..

composable("detail/{item}",
            arguments = listOf(navArgument("item") {
                type = NavType.StringType
            })
        ) {
            it.arguments?.getString("item")?.let { jsonString ->
                val user = jsonString.fromJson(User::class.java)
                DetailScreen( navController = navController, user = user )
            }
          }

Now navigate by passing string..

  val userString = user.toJson()
  navController.navigate(detail/$userString")

EDIT: There is also a limit for the Json-String that you can navigate. If the length of the Json-String is tooo long then the NavController won't recognize your Composable Route eventually throw an exception... Another work around would be to use a Global Variable and set its value in before navigating.. then pass this value as arguments in your Composable Functions..

 var globalUser : User? = null // global object somewhere in your code
    .....
    .....
    // While Navigating
    click { user->
            globalUser = user
            navController.navigate(detail/$userString")
          }

    // Composable
    composable( "detail") {
            DetailScreen(
                navController = navController,
                globalUser)
             }

NOTE :-> ViewModels can also be used to achieve this..

Let me give you very simple answers. We have different options like.

  1. Using Arguments but issue with this is that you can't share long or complex objects, only simple types like Int, String, etc. Now you are thinking about converting objects to JsonString and trying to pass it, but this trick only works for small or easy objects. Exception look like this:

    java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri="VERY LONG OBJECT STRING" } cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0x2e9fc7db) route=Screen_A}

  2. Now we have a Parsable Type in navArgument, but we need to put that object in current backStack and need to retrieve from next screen. The problem with this solution is you need keep that screen in your backStack. You can't PopOut your backStack. Like, if you want to popout your Login Screen when you navigate to Main Screen, then you can't retrieve Object from Login Screen to Main Screen.

  3. You need to Create SharedViewModel. Make sure you only use shared state and only use this technique when above two are not suitable for you.

Related