Ahmed
03/05/2025, 5:55 PMsavedStateHandle
and toRoute
api. More in 🧵Ahmed
03/05/2025, 5:55 PMnavigation<MyGraph> (startDestination = A) {
composable<A> {
val vm = hiltViewModel<VMA>()
}
composable<B> {
val vm = hiltViewModel<VMB>()
}
}
and I navigate via
fun NavController.navigateToMyGraph(myInt: Int) {
navigate(MyGraph(myInt = myInt))
}
In my VMA
I can obtain MyGraph
by doing savedStateHandle.toRoute<MyGraph>()
and I can obtain myInt
as well. But I am unable to do so in VMB
and I encounter the following crash.
kotlinx.serialization.MissingFieldException: Fields [myInt] are required for type with serial name '<MY_PACKAGE_NAME>.MyGraph', but they were missing
at kotlinx.serialization.internal.PluginExceptionsKt.throwMissingFieldException(PluginExceptions.kt:20)
at <MY_PACKAGE_NAME>.MyGraph.<init>(Routes.kt:6)
at <MY_PACKAGE_NAME>.MyGraph$$serializer.deserialize(Routes.kt:6)
at <MY_PACKAGE_NAME>.MyGraph$$serializer.deserialize(Routes.kt:6)
What am I doing wrong here or what am i missing?Ahmed
03/05/2025, 5:57 PMMyGraph
. But the issue is that it defaults to the given value, and I am unable to retrieve the actual myInt
.Ian Lake
03/05/2025, 6:10 PMtoRoute<MyGraph>()
is with getBackStackEntry<MyGraph>()
or in ViewModels scoped to getBackStackEntry<MyGraph>()
It only accidentally works in A
because we pass arguments down the the start destination and you just happen to use the same field nameAhmed
03/05/2025, 6:24 PMval myGraph = remember(navBackStackEntry) {
navController.getBackStackEntry<MyGraph>().toRoute<MyGraph>()
}
So, this would be more appropriate. Thanks!Ian Lake
03/05/2025, 6:26 PM