I have a screen that receives a parameter. From this screen, I navigate to multiple other screens, and eventually, I want to return to the initial screen. However, since the initial screen requires a parameter, I need to pass it when navigating back.
I am using type-safe navigation in Jetpack Compose, and my initial screen is defined like this:
@Serializable
sealed class MyGraph {
@Serializable
data class MainScreen(val isNew: Boolean) : MyGraph()
}
To navigate back to the initial screen after moving through multiple screens, I tried the following approach:
navController.navigate(MyGraph.MainScreen){
popUpTo<MyGraph.MainScreen>(){ inclusive = false }
launchSingleTop = true
}
However, I receive the following error:
kotlinx.serialization.SerializationException: Serializer for class 'Companion' is not found.
Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.
I was expecting this to navigate directly back to the screen I had on the stack (with the parameter it had already received previously)
Your issue isn't with the popUpTo
part, it is with the navigate(MyGraph.MainScreen)
part - you are navigating to a new instance of MyGraph.MainScreen
but using the class as an object (e.g., the Companion
of that class) and not an instance of the class.
Calling navigate
always adds something new to the stack (even for launchSingleTop
, it does a 'replace' kind of operation).
If you just want to pop, you should be using popBackStack
:
navController.popBackStack<MyGraph.MainScreen>(inclusive = false)