Expand description
Opt-in persistable state trait for widgets. Opt-in trait for widgets with persistable state.
The Stateful trait defines a contract for widgets that can save and
restore their state across sessions or configuration changes. It is
orthogonal to StatefulWidget — a widget can
implement both (render-time state mutation + persistence) or just one.
§Design Invariants
-
Round-trip fidelity:
restore_state(save_state())must produce an equivalent observable state. Fields that are purely derived (e.g., cached layout) may differ, but user-facing state (scroll position, selection, expanded nodes) must survive the round trip. -
Graceful version mismatch: When
VersionedStatedetects a version mismatch (stored.version != T::state_version()), the caller should fall back toT::State::default()rather than panic. Migration logic belongs in the downstream state migration system (bd-30g1.5). -
Key uniqueness: Two distinct widget instances must produce distinct
StateKeyvalues. The(widget_type, instance_id)pair is the primary uniqueness invariant. -
No side effects:
save_statemust be a pure read;restore_statemust only mutateself(no I/O, no global state).
§Failure Modes
| Failure | Cause | Fallback |
|---|---|---|
| Deserialization error | Schema drift, corrupt data | Use Default::default() |
| Version mismatch | Widget upgraded | Use Default::default() |
| Missing state | First run, key changed | Use Default::default() |
| Duplicate key | Bug in state_key() impl | Last-write-wins (logged) |
§Feature Gate
This module is always available, but the serde-based VersionedState
wrapper requires the state-persistence feature for serialization support.
Structs§
- Migration
Chain - A chain of migrations that can upgrade state through multiple versions.
- State
Key - Unique identifier for a widget’s persisted state.
- Versioned
State - Version-tagged wrapper for serialized widget state.
Enums§
- Migration
Error - Error that can occur during state migration.
- Restore
Result - Result of attempting state restoration with migration.
Traits§
- Erased
Migration - A type-erased migration step for use in migration chains.
- State
Migration - A single-step migration from version N to version N+1.
- Stateful
- Opt-in trait for widgets with persistable state.