register<T> static method

void register<T>({
  1. required String key,
  2. required Map<String, dynamic> exporter(),
  3. required void importer(
    1. Map<String, dynamic>
    ),
})

Registers a state contributor with the checkpoint system.

This method registers a state handler that can export and import application state. The state will be included in snapshots and can be restored from snapshots.

Example:

StateSnapshot.register<UserState>(
  key: 'user_state',
  exporter: () => userState.toJson(),
  importer: (json) => userState.restore(json),
);

Requirements:

  • Checkpoint must be enabled (see enable)
  • key must be unique (not already registered)
  • exporter must be pure (no side effects, deterministic)
  • importer must be idempotent (safe to call multiple times)
  • Both functions must work with JSON-serializable data only

State Safety Rules:

The exported state must be JSON-serializable and must NOT contain:

  • BuildContext or widget references
  • ❌ Streams, Controllers, Futures, or async handles
  • ❌ Platform handles (File, Socket, Database connections, etc.)
  • ❌ Closures or functions
  • ❌ Circular references

Allowed types: Map, List, String, num (int/double), bool, null

Validation: State is automatically validated during capture. If validation fails, a StateError will be thrown with a clear error message indicating the problematic path and type.

Example of invalid state:

// ❌ BAD - Contains BuildContext
exporter: () => {'context': context}

// ❌ BAD - Contains Stream
exporter: () => {'stream': myStream}

// ✅ GOOD - Only JSON-serializable data
exporter: () => {'name': 'John', 'age': 30}

Type Parameter:

  • T: The type of the state object being contributed (used for type safety and documentation, but not enforced at runtime).

Parameters:

  • key: Unique string identifier for this state contributor
  • exporter: Function that exports state as Map<String, dynamic>
  • importer: Function that imports state from Map<String, dynamic>

Throws:

Implementation

static void register<T>({
  required String key,
  required Map<String, dynamic> Function() exporter,
  required void Function(Map<String, dynamic>) importer,
}) {
  ensureEnabled();

  SnapshotRegistry.instance.register(key, exporter, importer);
}