pub trait StatefulWidget {
type State;
// Required method
fn render(&self, area: Rect, frame: &mut Frame<'_>, state: &mut Self::State);
}Expand description
A widget that renders based on mutable state.
Use StatefulWidget when the widget needs to:
- Update scroll position during render
- Track selection state
- Cache computed layout information
- Synchronize view with external model
§Example
ⓘ
pub struct ListState {
pub selected: Option<usize>,
pub offset: usize,
}
impl StatefulWidget for List<'_> {
type State = ListState;
fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
// Adjust offset to keep selection visible
if let Some(sel) = state.selected {
if sel < state.offset {
state.offset = sel;
}
}
// Render items starting from offset...
}
}§Stateful vs Stateless
Prefer stateless Widget when possible. Use StatefulWidget only when
the render pass genuinely needs to modify state (e.g., scroll adjustment).
Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".