Hi all, i am trying out compose navigation with sa...
# compose
k
Hi all, i am trying out compose navigation with safe args in the latest navigation compose androidx lib version 2.8.0-alpha08. Everything is going fine except i cannot find out how to make a custom NavType nullable. I read https://medium.com/androiddevelopers/navigation-compose-meet-type-safety-e081fb3cf2f8 . below is my Route navigation classes.
Copy code
@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.
Copy code
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
Copy code
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
Copy code
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
Copy code
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?
🎉 4
👍 1
🚀 3
👋 1
i
I think your
serializeAsValue
is probably missing a
Uri.encode
around your
encodeToString
- you aren't escaping the special characters there
But if that doesn't help, I'd suggest filing a bug with a sample project: https://issuetracker.google.com/issues/new?component=409828&amp;template=1093757
320 Views