pub trait Stateful: Sized {
type State: Default;
// Required methods
fn state_key(&self) -> StateKey;
fn save_state(&self) -> Self::State;
fn restore_state(&mut self, state: Self::State);
// Provided method
fn state_version() -> u32 { ... }
}Expand description
Opt-in trait for widgets with persistable state.
Implementing this trait signals that a widget’s user-facing state can be serialized, stored, and later restored. This is used by the state registry (bd-30g1.2) to persist widget state across sessions.
§Relationship to StatefulWidget
StatefulWidget: render-time mutable state (scroll clamping, layout cache).Stateful: persistence contract (save/restore across sessions).
A widget can implement both when its render-time state is also worth persisting.
§Example
use serde::{Serialize, Deserialize};
use ftui_widgets::stateful::{Stateful, StateKey};
#[derive(Serialize, Deserialize, Default)]
struct ScrollViewPersist {
scroll_offset: u16,
}
impl Stateful for ScrollView {
type State = ScrollViewPersist;
fn state_key(&self) -> StateKey {
StateKey::new("ScrollView", &self.id)
}
fn save_state(&self) -> Self::State {
ScrollViewPersist { scroll_offset: self.offset }
}
fn restore_state(&mut self, state: Self::State) {
self.offset = state.scroll_offset.min(self.max_offset());
}
}Required Associated Types§
Required Methods§
Sourcefn state_key(&self) -> StateKey
fn state_key(&self) -> StateKey
Unique key identifying this widget instance.
Two distinct widget instances must return distinct keys.
Sourcefn save_state(&self) -> Self::State
fn save_state(&self) -> Self::State
Extract current state for persistence.
This must be a pure read — no side effects, no I/O.
Sourcefn restore_state(&mut self, state: Self::State)
fn restore_state(&mut self, state: Self::State)
Restore state from persistence.
Implementations should clamp restored values to valid ranges (e.g., scroll offset ≤ max offset) rather than trusting stored data.
Provided Methods§
Sourcefn state_version() -> u32
fn state_version() -> u32
State schema version for forward-compatible migrations.
Bump this when the State type’s serialized form changes in a
backwards-incompatible way. The state registry will discard stored
state with a mismatched version and fall back to Default.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".