Implementation
Make sure to annotate destinations and custom parcelables with @Serializable
[versions]
kotlinxSerializationJson = "1.6.3"
kotlinxSerialization = "1.9.0"
navigationCompose = "2.8.0-alpha08"
[libraries]
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
[plugins]
jetbrains-kotlin-serialization = { id ="org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlinxSerialization"}
plugins {
alias(libs.plugins.jetbrains.kotlin.serialization) apply false
}
plugins {
alias(libs.plugins.jetbrains.kotlin.serialization)
id("kotlin-parcelize")
}
depencencies {
implementation(libs.androidx.navigation.compose)
implementation(libs.kotlinx.serialization.json)
}
// Defines a home destination that doesn't take any arguments
@Serializable
object Home
// Defines a profile destination that takes an ID
@Serializable
data class Profile(val id: String)
NavHost(navController = navController, startDestination = Home) {
composable<Home> {
HomeScreen()
}
composable<Profile> { backStackEntry: NavBackStackEntry ->
val args = backStackEntry.toRoute<Profile>()
ProfileScreen(id = args.id)
}
}
- Annotate your
data class
with@Parcelize
and implementParcelable
interface - Define Custom
NavType
for thatdata class
- Generic mapper for CustomNavType
@Serializable
@Parcelize
data class User(val name: String, val age: Int) : Parcelable
composable<Profile>(
typeMap = mapOf(typeOf<User>() to CustomNavType(User::class.java, User.serializer()))
) { backStackEntry: NavBackStackEntry ->
val args = backStackEntry.toRoute<Profile>()
ProfileScreen(user = args.user)
}