Trait ratatui::widgets::StatefulWidgetRef

source ·
pub trait StatefulWidgetRef {
    type State;

    // Required method
    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State);
}
Available on crate feature unstable-widget-ref only.
Expand description

A StatefulWidgetRef is a trait that allows rendering a stateful widget by reference.

This is the stateful equivalent of WidgetRef. It is useful when you want to store a reference to a stateful widget and render it later. It also allows you to render boxed stateful widgets.

This trait was introduced in Ratatui 0.26.0 and is implemented for all the internal stateful widgets. Implementors should prefer to implement this over the StatefulWidget trait and add an implementation of StatefulWidget that calls StatefulWidgetRef::render_ref where backwards compatibility is required.

A blanket implementation of StatefulWidget for &W where W implements StatefulWidgetRef is provided.

See the documentation for WidgetRef for more information on boxed widgets. See the documentation for StatefulWidget for more information on stateful widgets.

§Examples

use ratatui::{prelude::*, widgets::*};

struct PersonalGreeting;

impl StatefulWidgetRef for PersonalGreeting {
    type State = String;
    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        Line::raw(format!("Hello {}", state)).render(area, buf);
    }
}

impl StatefulWidget for PersonalGreeting {
    type State = String;
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        (&self).render_ref(area, buf, state);
    }
}

fn render(area: Rect, buf: &mut Buffer) {
    let widget = PersonalGreeting;
    let mut state = "world".to_string();
    widget.render(area, buf, &mut state);
}

§Availability

This API is marked as unstable and is only available when the unstable-widget-ref crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

Required Associated Types§

source

type State

State associated with the stateful widget.

If you don’t need this then you probably want to implement WidgetRef instead.

Required Methods§

source

fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State)

Draws the current state of the widget in the given buffer. That is the only method required to implement a custom stateful widget.

Implementors§