As I see in NavType docs, there is a sub-type called NavType.SerializableType which:
Is used for Serializable NavArguments.
The SerializableType's class constructor takes an argument of type Class<D?>?
which should be a:
class that is a subtype of Serializable.
Now, I have the following class:
data class Product (
var key: String? = null,
//Other 15 different fields.
): Serializable
Here is how the NavHost looks like:
NavHost(
navController = navController,
startDestination = "Products"
) {
composable(
route = "Products"
) {
ProductsScreen(
navController = navController
)
}
composable(
route = "Product/{product}",
arguments = listOf(
navArgument("product") {
type = NavType.SerializableType(Product::class.java)
}
)
) {
val product = navController.previousBackStackEntry?.arguments?.getSerializable("product") as Product
ProductScreen(
navController = navController,
product = product
)
}
And I navigate from inside the start destination (Products screen) to (Product screen) using inside the :
navController.currentBackStackEntry?.arguments?.putSerializable("product", product)
navController.navigate("Product/${product}")
I get a crash with this errror:
Serializables don't support default values.
However, if I change the above by removing /{product}
:
NavHost(
navController = navController,
startDestination = "Products"
) {
composable(
route = "Products"
) {
ProductsScreen(
navController = navController
)
}
composable(
route = "Product",
arguments = listOf(
navArgument("product") {
type = NavType.SerializableType(Product::class.java)
}
)
) {
val product = navController.previousBackStackEntry?.arguments?.getSerializable("product") as Product
ProductScreen(
navController = navController,
product = product
)
}
And navigate as explained here:
navController.currentBackStackEntry?.arguments?.putSerializable("product", product)
navController.navigate("Product")
I get:
java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/Product } cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0xb543811) route=Products}
How can I add a Serializable object of type Product to NavArguments and get back correctly? I don't want to transform the object to JSON String. Is this even possible?