NavBackStackSerializer


public final class NavBackStackSerializer<T extends NavKey>


A KSerializer for NavBackStack.

This serializer wraps a KSerializer for the element type T, enabling serialization and deserialization of NavBackStack instances. The serialization of individual elements is delegated to the provided elementSerializer.

If your stack elements T are open polymorphic (e.g., a interface for different screens), the provided elementSerializer must be correctly configured to handle this.

import androidx.navigation3.runtime.NavBackStack
import androidx.navigation3.runtime.samples.RememberNavBackStackSamples.Details
import androidx.navigation3.runtime.samples.RememberNavBackStackSamples.Home
import androidx.navigation3.runtime.samples.RememberNavBackStackSamples.Screen
import androidx.navigation3.runtime.serialization.NavBackStackSerializer
import androidx.savedstate.serialization.decodeFromSavedState
import androidx.savedstate.serialization.encodeToSavedState

// On Android, the no-argument overload uses reflection and requires no configuration.
// This will throw a runtime exception on non-Android platforms during serialization.
val serializer = NavBackStackSerializer<Screen>()

val backStack = NavBackStack(Home("abc"), Details(42))
val encoded = encodeToSavedState(serializer, backStack)
val decoded = decodeFromSavedState(serializer, encoded)
Parameters
<T extends NavKey>

The type of elements stored in the NavBackStack.

Summary

Public constructors

<T extends NavKey> NavBackStackSerializer(
    @NonNull <Error class: unknown class><@NonNull T> elementSerializer
)

Public constructors

public <T extends NavKey> NavBackStackSerializer(
    @NonNull <Error class: unknown class><@NonNull T> elementSerializer
)
Parameters
<T extends NavKey>

The type of elements stored in the NavBackStack.

@NonNull <Error class: unknown class><@NonNull T> elementSerializer

The KSerializer used to serialize and deserialize individual elements.

Public methods

serialize

public void serialize(
    @NonNull <Error class: unknown class> encoder,
    @NonNull NavBackStack<@NonNull T> value
)