Kenneth Leong
05/05/2024, 6:32 AM@Serializable
@SerialName(ABOUT_ROUTE_NAME)
data class ABOUT(val someArg: ABOUT_ARG? = null): Route()
@Parcelize
@Serializable
@SerialName(ABOUT_ARG_ROUTE_NAME)
data class ABOUT_ARG(val inner_arg: String, val inner_list_arg: List<String>): Parcelable
During the navigation of the navgraph, somehow the kotlinx serialization will always seem to require me to have ABOUT_ARG
as if its was not optional.
below is my custom NavTypes implementaton.
val ABOUT_ARG_Type = object : NavType<ABOUT_ARG?>(
isNullableAllowed = true
) {
override fun serializeAsValue(value: ABOUT_ARG?): String {
return value?.run { Json.encodeToString(ABOUT_ARG.serializer(), this) } ?: ""
}
override fun put(bundle: Bundle, key: String, value: ABOUT_ARG?) {
bundle.putParcelable(key, value)
}
override fun get(bundle: Bundle, key: String): ABOUT_ARG? {
return if (VERSION.SDK_INT >= VERSION_CODES.TIRAMISU) {
bundle.getParcelable(key, ABOUT_ARG::class.java)
} else {
bundle.getParcelable(key)
}
}
override fun parseValue(value: String): ABOUT_ARG? {
if (value.isEmpty()) return null
val parsed = Json.decodeFromString<ABOUT_ARG>(value)
return parsed
}
}
and here is how i set my navtypes to the navigation composable
composable<ABOUT>(typeMap = mapOf(typeOf<ABOUT_ARG?>() to ABOUT_ARG_Type)) {
val someArg = backStackEntry.toRoute<ABOUT>().someArg
Log.d("ABOUT SCREEN", "$someArg")
AboutAppScreen(contentPadding = contentPadding)
}
and below is how i navigate to it
navController.navigate(ABOUT(ABOUT_ARG("from settings", listOf("test1", "test2"))))
When navigating to it, it seems to crash with an exception below, despite i already setting that argument to nullable with a default value
kotlinx.serialization.MissingFieldException: Fields [inner_arg, inner_list_arg] are required for type with serial name 'ABOUT_ARG_ROUTE_NAME', but they were missing
Can anyone enlighten me?Ian Lake
05/05/2024, 2:03 PMserializeAsValue
is probably missing a Uri.encode
around your encodeToString
- you aren't escaping the special characters thereIan Lake
05/05/2024, 2:04 PM