Getting a crash when I try to obtain my route via ...
# compose-android
a
Getting a crash when I try to obtain my route via
savedStateHandle
and
toRoute
api. More in 🧵
If I have the following structure of navigation
Copy code
navigation<MyGraph> (startDestination = A) {
  composable<A> {
    val vm = hiltViewModel<VMA>()
  }

  composable<B> {
    val vm = hiltViewModel<VMB>()
  }
}
and I navigate via
Copy code
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.
Copy code
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?
On a side note, this works fine if I specify default values for
MyGraph
. But the issue is that it defaults to the given value, and I am unable to retrieve the actual
myInt
.
i
The only place you should be using
toRoute<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 name
👍 1
a
Ah! So I should rather obtain it in composable.
Copy code
val myGraph = remember(navBackStackEntry) {
  navController.getBackStackEntry<MyGraph>().toRoute<MyGraph>()
}
So, this would be more appropriate. Thanks!
i
Yep, looks good to me