Function rui::state

source ·
pub fn state<S: 'static, V: View, D: Fn() -> S + 'static, F: Fn(StateHandle<S>, &Context) -> V + 'static>(
    initial: D,
    f: F
) -> impl View
Expand description

State allows you to associate some state with a view. This is what you’ll use for a data model, as well as per-view state. Your state should be efficiently clonable. Use Rc as necessary.

initial is the initial value for your state.

f callback which is passed a State<S>

Examples found in repository?
examples/toggle.rs (line 4)
3
4
5
fn main() {
    rui(state(|| false, |s, _| toggle(s)));
}
More examples
Hide additional examples
examples/gallery.rs (line 11)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fn slider_example() -> impl View {
    hstack((caption("slider"), state(|| 0.5, |s, _| hslider(s))))
}

fn caption(s: &'static str) -> impl View {
    s.font_size(12).padding(Auto)
}

fn knob_example() -> impl View {
    hstack((
        caption("knob"),
        state(|| 0.5, |s, _| knob(s).size([30.0, 30.0]).padding(Auto)),
    ))
}

fn toggle_example() -> impl View {
    hstack((
        caption("toggle"),
        state(|| false, |s, _| toggle(s).size([30.0, 30.0]).padding(Auto)),
    ))
}

fn text_editor_example() -> impl View {
    hstack((
        caption("text_editor"),
        state(
            || "edit me".to_string(),
            |txt, _| text_editor(txt).padding(Auto),
        ),
    ))
}
examples/slider.rs (lines 19-25)
18
19
20
21
22
23
24
25
26
fn main() {
    rui(state(MyState::default, |state_handle, cx| {
        map(
            cx[state_handle].value,
            move |v, cx| cx[state_handle].value = v,
            |s, _| my_slider(s),
        )
    }));
}
examples/lens.rs (lines 11-18)
10
11
12
13
14
15
16
17
18
19
fn main() {
    rui(state(MyState::default, |state, cx| {
        vstack((
            cx[state].value.font_size(10).padding(Auto),
            hslider(bind(state, ValueLens {}))
                .thumb_color(RED_HIGHLIGHT)
                .padding(Auto),
        ))
    }));
}
examples/font_size.rs (lines 4-14)
3
4
5
6
7
8
9
10
11
12
13
14
15
fn main() {
    rui(state(
        || 0.0,
        |size, cx| {
            let s = (cx[size] * 100.0) as u32;
            vstack((
                "58".font_size(s),
                format!("font size: {}", s),
                hslider(size),
            ))
        },
    ));
}
examples/counter.rs (lines 4-15)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {
    rui(state(
        || 1,
        |count, cx| {
            vstack((
                cx[count].padding(Auto),
                button("increment", move |cx| {
                    cx[count] += 1;
                })
                .padding(Auto),
            ))
        },
    ));
}