NavBackStackKt


public final class NavBackStackKt


Summary

Public methods

static final @NonNull SnapshotStateList<@NonNull NavKey>
@Composable
<T extends NavKey> rememberNavBackStack(
    @NonNull T... elements,
    @NonNull SavedStateConfiguration configuration
)

Provides a NavBackStack that is automatically remembered in the Compose hierarchy across process death and configuration changes.

Public methods

rememberNavBackStack

@Composable
public static final @NonNull SnapshotStateList<@NonNull NavKey> <T extends NavKey> rememberNavBackStack(
    @NonNull T... elements,
    @NonNull SavedStateConfiguration configuration
)

Provides a NavBackStack that is automatically remembered in the Compose hierarchy across process death and configuration changes.

This function uses NavBackStackSerializer under the hood to save and restore the back stack via rememberSerializable.

Serialization requirements

  • Each element placed in the NavBackStack must be @Serializable.

  • For closed polymorphism (sealed hierarchies), the compiler knows all subtypes and generates serializers automatically. No custom SavedStateConfiguration is required.

  • For open polymorphism (interfaces or non-sealed hierarchies):

    • On Android, SavedStateConfiguration.DEFAULT uses a reflective serializer that can handle subtypes without registration.

    • On other platforms, or when you supply a custom configuration, you must register all subtypes of NavKey in a SerializersModule and pass that via configuration. You must also provide the same configuration to the encoder/decoder when saving/restoring state.

Example

@Serializable sealed interface Screen : NavKey
@Serializable data class Home(val id: String) : Screen
@Serializable data class Details(val itemId: Long) : Screen

// Closed polymorphism with sealed interface works out of the box on Android:
val backStack = rememberNavBackStack(Home("start"))

// Open polymorphism requires registering subtypes (non-Android):
val module = SerializersModule {
polymorphic(Screen::class) {
subclass(Home::class, Home.serializer())
subclass(Details::class, Details.serializer())
}
}
val config = SavedStateConfiguration(serializersModule = module)
val backStack = rememberNavBackStack(Home("start"), configuration = config)
Parameters
@NonNull T... elements

The initial keys of this back stack.

@NonNull SavedStateConfiguration configuration

Controls how element serializers are resolved. On Android, SavedStateConfiguration.DEFAULT uses reflection; otherwise, the provided SerializersModule is used.

Returns
@NonNull SnapshotStateList<@NonNull NavKey>

A NavBackStack that survives process death and configuration changes.