Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

FLUI

FLUI is a declarative UI framework for Rust, inspired by Flutter’s widget-style composition. Its pipeline is a tree design — immutable View configuration → mutable Element lifecycle → layout/paint RenderObject → a Layer tree built each frame, with a Semantics tree alongside for accessibility → flui-engine compositor → wgpu GPU — with structure and APIs designed for Rust. Cross-crate decisions are recorded as ADRs. See AGENTS.md’s Design stance for the full policy.

This book teaches the current development version of FLUI. Start with a checkout and the installation guide; what each platform has been run on is recorded in the repository’s platform status. API and feature choices can change between releases.

The book is incomplete. Chapters link to the working examples and reference material where more detail is needed. Every Rust sample compiles and runs against the flui crate as a test of the repository; the linked source has the required features.

Where to start

Find the right reference

NeedSource
Runnable applications and feature flagsExample commands
Public types and method contracts for your checkoutRun cargo doc -p flui --no-deps --open; enable the same features as your application.
Widget discoveryWidget catalog
Testing an application without a native windowTesting recipe
Design decisions and crate boundariesArchitecture
Current release requirementsRelease requirements
Which platforms have been run, and where FLUI falls shortPlatform status and gaps

The repository contains this book’s source. Use the edit button on a chapter to propose a documentation correction.

Installation and first run

This page covers the app-author path: install the toolchain, generate an application with flui create, and run it. For the fuller reference (full prerequisites table, every bundled example, troubleshooting) see docs/getting-started.md in the repository.

If you want to work on FLUI itself rather than build an app with it, see Contributing to FLUI instead — the setup is different (a workspace checkout, not a generated application).

Prerequisites

ToolMinimum versionNotes
Rust via rustup1.100The checkout pins 1.100.0 in rust-toolchain.toml; an application outside it needs its own toolchain selection (below).
Gitany recentUsed to clone FLUI and initialize the generated application.
Native toolchainplatform-specificMSVC on Windows, Xcode CLT on macOS, NDK on Android (only if targeting Android).

The flui CLI is published on crates.io as flui-cli (cargo install flui-cli --locked); the framework crates are not. A project generated by a crates.io CLI depends on the FLUI git tag that matches the CLI’s version, and the first cargo build clones it. This page instead builds the CLI from a checkout and generates an application against that checkout’s source (--local), so the CLI and the framework share one source tree.

Install the CLI and create an app

Clone the flui repository, then install its CLI:

git clone https://github.com/vanyastaff/flui
cd flui
cargo install --path crates/flui-cli --locked
flui create my_app --local --path ../apps --no-check
cd ../apps/my_app
rustup override set 1.100.0
cargo check
flui doctor
flui run

--no-check postpones the scaffold’s compile check until you have selected the application’s toolchain. The generated project does not contain a rust-toolchain.toml, and a path dependency on FLUI does not select the checkout’s toolchain for it. rustup override set selects Rust for this application directory; it leaves your global default unchanged. Run the commands one at a time and fix any failed check before proceeding to flui run.

The default template is counter. A desktop window should show a count and an Increment button. Press the button to update the count; close the window to exit. The application lives in src/lib.rs; src/main.rs mounts its root with flui::run_app. The template also generates headless interaction tests: run cargo test from the application directory to exercise them.

The generated application can live outside the FLUI repository. Bare --local uses the current directory as its source checkout; from another directory, use --local=/path/to/flui. The source must remain available afterward — the generated flui dependency points at the checkout root by absolute path. flui is the application’s only framework dependency; UI code starts with use flui::prelude::*;. No design system is on by default: to use flui::material or flui::cupertino, add features = ["material"] (or "cupertino") to the flui dependency in the generated Cargo.toml.

flui run reloads an edit of the generated application’s code on Linux, macOS and Windows, keeping each State whose layout the edit left alone; an edit to its manifest or dependencies restarts it, and neither needs anything in the project (hot reload). See the CLI guide for template and build options.

Run a bundled example instead

To try FLUI without generating a project first, run one of the bundled examples from the repository checkout:

cargo run --locked --example counter

A window opens showing a count and an “Increment” button — the same shape flui create’s counter template generates. See the full example table and web/Android instructions in docs/getting-started.md.

Diagnose a failed first run

Run flui doctor --verbose from the application directory to inspect the selected Rust version and tool paths. Optional Android, iOS, and Web tooling can produce warnings without blocking a desktop app. For a target-specific check, use flui doctor --android, --ios, or --web.

SymptomNext step
flui command not found after installationPut Cargo’s binary directory on PATH (~/.cargo/bin, or %USERPROFILE%\.cargo\bin on Windows), then open a new terminal.
Rust version below 1.100Run rustup override set 1.100.0 in the application directory, then retry cargo check.
Windows cannot find or run link.exeInstall Visual Studio Build Tools with the Desktop development with C++ workload and Windows SDK.
flui::material or flui::cupertino import is unresolvedEnable the corresponding facade feature in the application’s Cargo.toml.
Local FLUI dependency cannot be foundKeep the source checkout at its original location, or update its absolute path in the application’s Cargo.toml.

For application logs, set RUST_LOG=flui_app=debug,flui_engine=debug before flui run (Bash: export RUST_LOG=flui_app=debug,flui_engine=debug; PowerShell: $env:RUST_LOG = "flui_app=debug,flui_engine=debug"). CLI diagnostics use flui -v run; they are separate from application logs. A release build from flui run --release or flui build --release holds application events up to info only, and says so in its log (a flui_log::ceiling warning) when RUST_LOG asks for more. A successful compile does not verify your window system or GPU: consult the platform status before choosing a deployment target.

Next steps

Contributing to FLUI

This page is for working on FLUI itself — its crates, its render pipeline, its CLI — not for building an application with it (see Installation and first run for that path instead).

The authoritative contributor references live in the repository, not duplicated here, so they stay in one place as they evolve:

  • AGENTS.md — the single agent/contributor guide: the design stance, worktree workflow, commands, enforced rules, and the Definition of Done.
  • CONTRIBUTING.md — planning a large change, git hygiene, reporting bugs, security.
  • docs/testing.md — the test pyramid, quality gates, and which CI job’s commands to run for what you touched.

Quick start

git clone https://github.com/vanyastaff/flui
cd flui
cargo build --workspace

Work happens in a dedicated git worktree per task (git worktree add), never the shared checkout; AGENTS.md’s “Working here” has the commit conventions. The local pre-PR checks run one at a time on the crates you changed (AGENTS.md, “Checking a change”):

cargo fmt --all
cargo clippy -p <crate> --all-targets -- -D warnings
cargo nextest run -p <crate>

This book

This site is itself a FLUI-workspace artifact, under book/. See .github/workflows/docs.yml for how it builds and deploys. A page here is a guide for readers; the design records and reference material stay in the repository’s own docs/, and the book links to them rather than copying them.

Every rust sample in the book compiles: src/book.rs makes each chapter a doctest of the flui facade, so cargo test -p flui --features testing,material,cupertino --doc book:: builds them all and runs the ones not marked no_run. A new chapter is listed there as well as in SUMMARY.md, setup a reader does not need goes on hidden # lines, and text that is not Rust is fenced text, never ignore.

Your first window

Flutter counterpart: runApp, StatelessWidget.

This tutorial builds a small notes application one chapter at a time. Each sample is a complete program; the ones that open a window are compiled but not run by the book’s tests.

A view and a window

An application is a tree of views. A view that only describes what it shows is a StatelessView: a struct holding its inputs and a build that returns its children.

use flui::prelude::*;

#[derive(Clone, StatelessView)]
struct NotesApp;

impl StatelessView for NotesApp {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Center::new().child(Text::new("No notes yet"))
    }
}

fn main() -> Result<(), LaunchError> {
    run_app(NotesApp)
}

run_app opens a main window with the view at its root and runs until the window closes. It returns a LaunchError when the application cannot start: the platform or its GPU is not available, or two plugins provide the same capability.

The derive writes the View implementation that mounts the struct; the impl StatelessView is the part you write.

Configuring the run

run_app(root) is Application::new().run(root). To set the window’s title and size, build the Application yourself and give it an AppConfig:

use flui::app::AppConfig;
use flui::prelude::*;

#[derive(Clone, StatelessView)]
struct NotesApp;
impl StatelessView for NotesApp {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Text::new("No notes yet")
    }
}
fn main() -> Result<(), LaunchError> {
    Application::new()
        .config(AppConfig::new().title("Notes").size(480, 640))
        .run(NotesApp)
}

The builder also registers plugins and capability providers; each method has the bare name of what it sets.

One entry for every platform

On the desktop, the web and iOS, the program starts from main. On Android the system loads the application as a library and calls an entry it exports. #[flui::main] writes that entry, so one function starts the application everywhere. A project from flui create puts it in src/lib.rs and calls it from src/main.rs:

use flui::prelude::*;

#[derive(Clone, StatelessView)]
struct NotesApp;
impl StatelessView for NotesApp {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Text::new("No notes yet")
    }
}
/// Start the application in a window with [`NotesApp`] as its root.
#[flui::main]
pub fn run() -> Result<(), LaunchError> {
    run_app(NotesApp)
}

fn main() -> Result<(), LaunchError> {
    run()
}

Next, Laying out a screen gives the window something to arrange.

Laying out a screen

Flutter counterpart: Column, Row, Padding, Expanded, SizedBox.

A screen is views arranged by layout views. Each layout view hands its children constraints and places them in the space they take (Layout has the protocol). The notes screen is a header above a list of note cards:

#![allow(unused)]
fn main() {
use flui::prelude::*;

/// One note in the list: its title, and how many words it has.
#[derive(Clone, StatelessView)]
struct NoteCard {
    title: String,
    words: usize,
}

impl StatelessView for NoteCard {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Padding::symmetric(16.0, 8.0).child(Row::new((
            // The title takes whatever width the count leaves.
            Expanded::new(Text::new(self.title.clone())),
            SizedBox::width(8.0),
            Text::new(format!("{} words", self.words)),
        )))
    }
}

#[derive(Clone, StatelessView)]
struct NotesScreen;

impl StatelessView for NotesScreen {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Column::new((
            Padding::all(16.0).child(Text::new("Notes")),
            NoteCard { title: "Groceries".to_owned(), words: 12 },
            NoteCard { title: "Talk outline".to_owned(), words: 240 },
        ))
    }
}
use flui::testing::scenario::{Tester, find};
let mut t = Tester::mount(NotesScreen);
// The window is 800 wide: both counts end 16 from its right edge, whatever
// the length of the title beside them.
let short = t.rect(&find::text("12 words"));
let long = t.rect(&find::text("240 words"));
assert_eq!(short.x + short.width, 784.0);
assert_eq!(long.x + long.width, 784.0);
}
  • Column and Row lay their children out along one axis, given as a tuple. A Row takes all the width its parent allows, so each card spans the window.
  • Expanded gives its child the space its siblings leave on the main axis, so the word count stays at the right edge however long the title is, and a long title wraps before it.
  • Padding and SizedBox make space: one around a child, the other between two.

A view is a plain struct, so a card is reused by building it with other inputs. The list here is fixed; Adding state makes it grow.

Adding state

Flutter counterpart: StatefulWidget, State, setState.

A view whose content changes keeps its changing part in a state. A StatefulView names its state type and creates it in create_state; the state’s build describes the view from it. The notes screen keeps its notes in a signal and adds one each time the button is pressed:

#![allow(unused)]
fn main() {
use flui::prelude::*;

#[derive(Clone, StatefulView)]
struct NotesScreen;

struct NotesState {
    notes: Signal<Vec<String>>,
}

impl StatefulView for NotesScreen {
    type State = NotesState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> NotesState {
        NotesState {
            notes: ctx.signal(Vec::new()),
        }
    }
}

impl ViewState<NotesScreen> for NotesState {
    fn build(&self, _view: &NotesScreen, ctx: &dyn BuildContext) -> impl IntoView {
        let notes = self.notes;
        let titles = notes.get(ctx);
        Column::new((
            Text::new(format!("Notes: {}", titles.len())),
            Column::new(titles.into_iter().map(Text::new).collect::<Vec<Text>>()),
            RawButton::new(Text::new("Add note")).on_pressed(move |ctx| {
                notes.update(ctx, |list| {
                    let title = format!("Note {}", list.len() + 1);
                    list.push(title);
                })
            }),
        ))
    }
}
use flui::testing::scenario::{Tester, find, matcher::exists};
let mut t = Tester::mount(NotesScreen);
t.expect(&find::text("Notes: 0"), exists());
t.tap(&find::button("Add note"));
t.tap(&find::button("Add note"));
t.expect(&find::text("Notes: 2"), exists());
t.expect(&find::text("Note 2"), exists());
}
  • The signal is created in create_state, so the state is born with it; ctx.signal is not available in build.
  • build reads the signal with get(ctx). The read subscribes this view, so a write rebuilds it and nothing else.
  • The button’s callback receives a ctx and writes through it with update, returning the write’s Result, so the button logs a refused write. build gets no context a write accepts, so a write there does not compile.
  • A Signal is a Copy handle, so the callback captures its own copy with move.

State covers the other forms of state: data shared down the tree with an InheritedView, and a ValueNotifier that code outside the tree listens to.

Next, Handling input lets the user name each note.

Handling input

Flutter counterpart: TextField, TextEditingController, onPressed.

A note needs a title the user types. A text field edits the text of a TextEditingController; the state that owns the controller reads it when the user adds the note:

#![allow(unused)]
fn main() {
use flui::prelude::*;

#[derive(Clone, StatefulView)]
struct NotesScreen;

struct NotesState {
    notes: Signal<Vec<String>>,
    title: TextEditingController,
}

impl StatefulView for NotesScreen {
    type State = NotesState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> NotesState {
        NotesState {
            notes: ctx.signal(Vec::new()),
            title: TextEditingController::new(),
        }
    }
}

impl ViewState<NotesScreen> for NotesState {
    fn build(&self, _view: &NotesScreen, ctx: &dyn BuildContext) -> impl IntoView {
        let notes = self.notes;
        let title = self.title.clone();
        let add = move |ctx: &mut EventContext<'_>| {
            let text = title.text().trim().to_owned();
            title.clear();
            if text.is_empty() {
                return Ok(());
            }
            notes.update(ctx, |list| list.push(text.clone()))
        };
        let titles = notes.get(ctx);
        let submit = add.clone();
        Column::new((
            Semantics::new()
                .label("New note")
                .identifier("new-note")
                .child(RawTextField::new(self.title.clone())
                    // Enter in the field adds the note too.
                    .on_submitted(move |ctx, _text| submit(ctx))),
            RawButton::new(Text::new("Add note")).on_pressed(add),
            Text::new(format!("Notes: {}", titles.len())),
            Column::new(titles.into_iter().map(Text::new).collect::<Vec<Text>>()),
        ))
    }
}
use flui::testing::scenario::{Tester, find, matcher::{exists, value}};
let mut t = Tester::mount(NotesScreen);
t.type_text(&find::id("new-note"), "Groceries");
t.tap(&find::button("Add note"));
t.expect(&find::text("Groceries"), exists());
t.expect(&find::id("new-note"), value(""));
// A blank title adds nothing.
t.type_text(&find::id("new-note"), "   ");
t.tap(&find::button("Add note"));
t.expect(&find::text("Notes: 1"), exists());
t.expect(&find::id("new-note"), value(""));
// Enter in the field adds what it holds.
t.type_text(&find::id("new-note"), "Talk outline");
t.press_keys(&["Enter"]);
t.expect(&find::text("Talk outline"), exists());
t.expect(&find::text("Notes: 2"), exists());
t.expect(&find::id("new-note"), value(""));
}
  • The controller is created with the state and shared by clone: the field edits it, the button’s callback reads and clears it.
  • A callback receives an EventContext, the ctx a signal write takes. The blank-title check returns before writing, so pressing the button with only spaces typed adds nothing.
  • The field’s on_submitted runs when the user presses Enter in it; it calls a clone of the same callback, since a closure whose captures are Clone is Clone too.
  • The Semantics label gives the field its accessible name, the one a screen reader announces, without showing a label on screen. Its identifier is a stable name for tests (find::id), which assistive technology never announces.

The button also activates from the keyboard when it has focus, with Enter or Space.

Next, Lists and keys shows the notes in a list that can grow past the window.

Lists and keys

Flutter counterpart: ListView.builder, ValueKey.

A list of notes can grow past the window. ListView::builder builds only the rows that are in view, asking its builder for the row at each index. Each row here has state of its own, whether it is open, and a key so that state stays with its note when a note above it is deleted:

#![allow(unused)]
fn main() {
use flui::prelude::*;
use flui::view::ValueKey;

#[derive(Clone, Default)]
struct Notes {
    next_id: u64,
    items: Vec<Note>,
}

#[derive(Clone)]
struct Note {
    id: u64,
    title: String,
}

#[derive(Clone, StatefulView)]
struct NotesScreen;

struct NotesState {
    notes: Signal<Notes>,
    title: TextEditingController,
}

impl StatefulView for NotesScreen {
    type State = NotesState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> NotesState {
        NotesState {
            notes: ctx.signal(Notes::default()),
            title: TextEditingController::new(),
        }
    }
}

impl ViewState<NotesScreen> for NotesState {
    fn build(&self, _view: &NotesScreen, ctx: &dyn BuildContext) -> impl IntoView {
        let notes = self.notes;
        let title = self.title.clone();
        let add = move |ctx: &mut EventContext<'_>| {
            let text = title.text();
            title.clear();
            notes.update(ctx, |list| {
                // Ids are never reused, so a key names one note for its life.
                let id = list.next_id;
                list.next_id += 1;
                list.items.push(Note { id, title: text.clone() });
            })
        };
        let items = notes.get(ctx).items;
        Column::new((
            RawTextField::new(self.title.clone()).identifier("new-note"),
            RawButton::new(Text::new("Add note")).on_pressed(add),
            Expanded::new(ListView::builder(items.len(), 48.0, move |index| {
                let note = items.get(index)?;
                Some(
                    NoteRow { key: ValueKey::new(note.id), note: note.clone(), notes }.boxed(),
                )
            })),
        ))
    }
}

/// One note: press its title to open it, or delete it.
#[derive(Clone, StatefulView)]
struct NoteRow {
    #[view(key)]
    key: ValueKey<u64>,
    note: Note,
    notes: Signal<Notes>,
}

struct NoteRowState {
    open: Signal<bool>,
}

impl StatefulView for NoteRow {
    type State = NoteRowState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> NoteRowState {
        NoteRowState { open: ctx.signal(false) }
    }
}

impl ViewState<NoteRow> for NoteRowState {
    fn build(&self, row: &NoteRow, ctx: &dyn BuildContext) -> impl IntoView {
        let open = self.open;
        let (notes, id) = (row.notes, row.note.id);
        let label = if open.get(ctx) {
            format!("{} (open)", row.note.title)
        } else {
            row.note.title.clone()
        };
        let toggle = move |ctx: &mut EventContext<'_>| open.update(ctx, |open| *open = !*open);
        let delete = move |ctx: &mut EventContext<'_>| {
            notes.update(ctx, |list| list.items.retain(|note| note.id != id))
        };
        Row::new((
            Expanded::new(RawButton::new(Text::new(label)).on_pressed(toggle)),
            RawButton::new(Text::new(format!("Delete {}", row.note.title))).on_pressed(delete),
        ))
    }
}
use flui::testing::scenario::{Tester, find, matcher::{exists, gone}};
let mut t = Tester::mount(NotesScreen);
for title in ["Groceries", "Talk outline"] {
    t.type_text(&find::id("new-note"), title);
    t.tap(&find::button("Add note"));
}
t.tap(&find::button("Talk outline"));
t.expect(&find::text("Talk outline (open)"), exists());
t.tap(&find::button("Delete Groceries"));
t.expect(&find::text("Groceries"), gone());
t.expect(&find::text("Talk outline (open)"), exists());
}
  • The builder returns None past the end of the data, and ? on items.get(index) says so.
  • A row’s key is its note’s id. When “Groceries” is deleted, “Talk outline” moves up one place; the key lets its element, and the open signal its state holds, move with it. Without the key the list would match rows by position, and the open row would close.
  • The row writes to the list’s signal, which it was given as a field: a Signal is a Copy handle, so passing it down is how a child changes its parent’s data.

Keys has the other key types. Next, Navigation gives each note a page of its own.

Navigation

Flutter counterpart: go_router’s GoRouter, ModalRoute.of, showDialog.

An application with more than one screen names its screens as routes. The routes are an enum, each variant with its path; a Router builds the page for the route on top, and the application hands it to WidgetsApp::router (or a design system’s MaterialApp::router):

#![allow(unused)]
fn main() {
use flui::prelude::*;

const NOTES: [&str; 2] = ["Groceries", "Talk outline"];

#[derive(Routable, Clone, Debug, PartialEq)]
enum NotesRoute {
    #[route("/")]
    List,
    #[route("/note/:id")]
    Note { id: usize },
}

fn app() -> WidgetsApp {
    WidgetsApp::router(Router::new(NotesRoute::List, |route: &NotesRoute, _ctx| match route {
        NotesRoute::List => NoteList.boxed(),
        NotesRoute::Note { id } => NotePage { id: *id }.boxed(),
    }))
}

/// Every note, each opening its own page.
#[derive(Clone, StatelessView)]
struct NoteList;

impl StatelessView for NoteList {
    fn build(&self, ctx: &dyn BuildContext) -> impl IntoView {
        let router = Router::<NotesRoute>::of(ctx).expect("BUG: the list is a page of the Router");
        let open = |id: usize| {
            let router = router.clone();
            RawButton::new(Text::new(format!("Open {}", NOTES[id])))
                .on_pressed(move |_ctx| {
                    let _ = router.push(NotesRoute::Note { id });
                })
        };
        Column::new((open(0), open(1)))
    }
}

/// One note: back to the list, or delete it after a confirmation.
#[derive(Clone, StatelessView)]
struct NotePage {
    id: usize,
}

impl StatelessView for NotePage {
    fn build(&self, ctx: &dyn BuildContext) -> impl IntoView {
        let page = PageHandle::of(ctx).expect("BUG: a note is a page of the Router");
        let back = page.clone();
        let confirm = move |_ctx: &mut EventContext<'_>| {
            let note = page.clone();
            let dialog = PopupRoute::<()>::new(move |ctx, _animation, _secondary| {
                let dialog = PageHandle::of(ctx).expect("BUG: the dialog is a route");
                let (cancel, note) = (dialog.clone(), note.clone());
                Column::new((
                    Text::new("Delete this note?"),
                    RawButton::new(Text::new("Cancel")).on_pressed(move |_ctx| {
                        let _ = cancel.pop();
                    }),
                    RawButton::new(Text::new("Delete note")).on_pressed(move |_ctx| {
                        // The dialog pops first, so the note's page is on top when it
                        // pops; the note pops only when the dialog's pop was taken.
                        if let Ok(true) = dialog.pop() {
                            let _ = note.pop();
                        }
                    }),
                ))
                .boxed()
            });
            let _ = page.push_popup(dialog);
        };
        Column::new((
            Text::new(NOTES[self.id]),
            RawButton::new(Text::new("Back")).on_pressed(move |_ctx| {
                let _ = back.pop();
            }),
            RawButton::new(Text::new("Delete")).on_pressed(confirm),
        ))
    }
}
use flui::testing::scenario::{Tester, find, matcher::{exists, gone}};
let mut t = Tester::mount(app());
t.tap(&find::button("Open Talk outline"));
t.expect(&find::text("Talk outline"), exists());
t.tap(&find::button("Delete"));
t.expect(&find::text("Delete this note?"), exists());
t.tap(&find::button("Delete note"));
let _settled = t.settle();
t.expect(&find::text("Delete this note?"), gone());
t.expect(&find::button("Back"), gone());
t.expect(&find::button("Open Groceries"), exists());
}
  • A page finds its router with Router::<R>::of(ctx) and its own route with PageHandle::of(ctx), in build. The handle moves into the callback, which runs after the build.
  • push opens a route over the current one, and its path becomes the window’s location; PageHandle::pop closes the page it was taken in.
  • A dialog is a PopupRoute pushed with push_popup. It has no path, so it never enters the URL, and the page below stays built and visible under it.
  • Each navigation call returns a Result: it is refused while the tree builds, or with PageError::Gone once the page has left its navigator. A press that lands while a page is on its way out gets Gone, which needs nothing done, so these callbacks drop the result. The dialog pops the note only when its own pop was taken, so a second press on a dialog already leaving does not pop the page under it.

Next, Theming gives the application its colours.

Theming

Flutter counterpart: MaterialApp, ThemeData, Theme.of.

A design system supplies finished widgets and a theme they read. The notes application uses the Material catalog, which flui’s material feature turns on. MaterialApp takes a light and a dark ThemeData and picks one by its ThemeMode; ThemeMode::System follows the platform’s setting:

#![allow(unused)]
fn main() {
use flui::prelude::*;

/// A header drawn in the theme's colours, whichever theme is in force.
#[derive(Clone, StatelessView)]
struct NotesHeader;

impl StatelessView for NotesHeader {
    fn build(&self, ctx: &dyn BuildContext) -> impl IntoView {
        let theme = Theme::of(ctx);
        let mode = if theme.brightness().is_dark() { "dark" } else { "light" };
        let style = theme.text_theme.title_large.clone().unwrap_or_default();
        Text::new(format!("Notes ({mode})")).style(style.with_color(theme.color_scheme.primary))
    }
}

fn app(mode: ThemeMode) -> MaterialApp {
    MaterialApp::new(Scaffold::new().body(NotesHeader))
        .theme(ThemeData::light())
        .dark_theme(ThemeData::dark())
        .theme_mode(mode)
}
use flui::testing::scenario::{Tester, find, matcher::exists};
Tester::mount(app(ThemeMode::Light)).expect(&find::text("Notes (light)"), exists());
Tester::mount(app(ThemeMode::Dark)).expect(&find::text("Notes (dark)"), exists());
}
  • Theme::of(ctx) reads the nearest theme above the view and makes the view depend on it, so a change of theme rebuilds it.
  • The catalog’s widgets (Scaffold, TextButton, TextField, AppBar) read the same theme, so the colours come from one place.
  • A theme of your own is a ThemeData with a different ColorScheme; Themes covers the rest.

Next, Testing checks the application the way a user would use it.

Testing

Flutter counterpart: testWidgets, WidgetTester, find.

A test of the application uses the screen as a user does: it finds what they see, acts on it, and expects what they should see next. flui::testing provides it under flui’s testing feature, which an application turns on for its tests:

[dev-dependencies]
flui = { version = "…", features = ["testing"] }

Here is a test of the notes screen from Handling input; a copy of the screen’s code is hidden above it:

#![allow(unused)]
fn main() {
use flui::prelude::*;

#[derive(Clone, StatefulView)]
struct NotesScreen;

struct NotesState {
    notes: Signal<Vec<String>>,
    title: TextEditingController,
}

impl StatefulView for NotesScreen {
    type State = NotesState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> NotesState {
        NotesState {
            notes: ctx.signal(Vec::new()),
            title: TextEditingController::new(),
        }
    }
}

impl ViewState<NotesScreen> for NotesState {
    fn build(&self, _view: &NotesScreen, ctx: &dyn BuildContext) -> impl IntoView {
        let notes = self.notes;
        let title = self.title.clone();
        let add = move |ctx: &mut EventContext<'_>| {
            let text = title.text().trim().to_owned();
            title.clear();
            if text.is_empty() {
                return Ok(());
            }
            notes.update(ctx, |list| list.push(text.clone()))
        };
        let titles = notes.get(ctx);
        let submit = add.clone();
        Column::new((
            Semantics::new()
                .label("New note")
                .identifier("new-note")
                .child(RawTextField::new(self.title.clone())
                    // Enter in the field adds the note too.
                    .on_submitted(move |ctx, _text| submit(ctx))),
            RawButton::new(Text::new("Add note")).on_pressed(add),
            Text::new(format!("Notes: {}", titles.len())),
            Column::new(titles.into_iter().map(Text::new).collect::<Vec<Text>>()),
        ))
    }
}
use flui::testing::scenario::matcher::{exists, value};
use flui::testing::scenario::{TestWindow, Tester, WindowSpec, find};

// In an application this is the body of a `#[test] fn adds_a_note()`.
let mut t = Tester::mount_in(NotesScreen, TestWindow::new(WindowSpec::new(360, 640)));
t.expect(&find::text("Notes: 0"), exists());

t.type_text(&find::id("new-note"), "Groceries");
t.tap(&find::button("Add note"));

t.expect(&find::text("Groceries"), exists());
t.expect(&find::text("Notes: 1"), exists());
t.expect(&find::id("new-note"), value(""));
t.finish();
}
  • Tester::mount mounts a view as run_app does, in an 800 by 600 window on a manual clock; mount_in takes a TestWindow built to a WindowSpec of another size, scale, platform or safe area. No window opens and no GPU is needed.
  • find builds a Find over what the screen exposes to assistive technology: find::text for a label, find::button for a button by its name, find::id for an element’s identifier. It names exactly one element: two matches fail the step with both listed, and .first(), .nth(n) or .all() says which one or how many you mean.
  • tap and type_text act through the window’s input path, after checking that the element is visible and enabled, as a user would find it.
  • expect(&find, exists()) waits while the application has a frame or work due, then fails at once with the window’s outline if what it expects is not there.
  • finish ends the test: it runs the end checks (work left due, a soft failure never raised) and fails the test with its report if one does not pass.

A screen where a Find matches nothing is usually one whose widget publishes no label; the failure’s outline shows what the window does publish. Testing in the cookbook covers time, storage and the other expectations.

Next, Platforms runs the application beyond the desktop.

Platforms

Flutter counterpart: flutter run -d, flutter build, defaultTargetPlatform.

The application written so far runs on every platform FLUI targets. The flui CLI builds and starts it on each:

flui devices              # what this machine can run on
flui run                  # this desktop
flui run --device <name>  # a phone, a simulator or a browser from `flui devices`
flui build android        # also ios, web, windows, linux, macos

Installation and first run lists what each target needs installed, and the repository’s platform status records what has been run on each.

A release build (flui build --release, flui run --release) is the one an application ships, and it holds no trace! or debug! call site, FLUI’s or the application’s: the CLI turns on the facade’s release-max-level-info feature, as flutter build compiles a release without its debug-only code. A plain cargo build --release keeps them, and so do a --profile profiling build and a flui run --agent build, whose timelines read the frame’s spans. An application that ships through cargo alone passes --features flui/release-max-level-info itself.

Following the platform’s conventions

Some details differ by platform: the shortcut a menu shows, where a dialog puts its buttons. A widget asks which platform’s conventions it follows with PlatformConvention::of(ctx), which the runtime installs above every root:

#![allow(unused)]
fn main() {
use flui::platform::TargetPlatform;
use flui::prelude::*;
use flui::view::environment::PlatformConvention;

/// The save hint under the notes list, in the platform's own words.
#[derive(Clone, StatelessView)]
struct SaveHint;

impl StatelessView for SaveHint {
    fn build(&self, ctx: &dyn BuildContext) -> impl IntoView {
        let chord = if PlatformConvention::of(ctx).is_apple() { "⌘S" } else { "Ctrl+S" };
        Text::new(format!("{chord} saves"))
    }
}
use flui::testing::scenario::{TestWindow, Tester, WindowSpec, find, matcher::exists};
let on = |platform| TestWindow::new(WindowSpec::new(800, 600).platform(platform));
Tester::mount_in(SaveHint, on(TargetPlatform::MacOS)).expect(&find::text("⌘S saves"), exists());
Tester::mount_in(SaveHint, on(TargetPlatform::Windows)).expect(&find::text("Ctrl+S saves"), exists());
// A subtree that names a platform follows it, whatever the window's.
let mac = PlatformConvention::new(TargetPlatform::MacOS, SaveHint);
Tester::mount_in(mac, on(TargetPlatform::Windows)).expect(&find::text("⌘S saves"), exists());
}

The convention is the platform the application runs on, unless a test or a subtree names another: a test names it in its WindowSpec (WindowSpec::platform), and a PlatformConvention::new(platform, child) above a subtree changes it for that subtree. TargetPlatform::current() is not a substitute: it is the target the code was compiled for, so it is Unknown in a browser whatever the visitor’s system, and in a test it is the target the test was compiled for rather than the platform the test names.

That completes the notes application: a window, a laid-out screen, state, input, a list, pages, a theme, its tests and its platforms.

The notes example in the repository puts the tutorial’s list, pages and theme together in one window, with the catalog’s TextField, TextButton and AlertDialog: cargo run --example notes --features material.

Concepts

FLUI uses declarative Rust values to describe UI. A new description does not mean throwing away all the UI’s state: reconciliation matches it to retained elements, which own lifecycle and state. Render objects then lay out and paint the result.

View → Element → RenderObject → Layer → flui-engine → wgpu
                    │
                    └→ Semantics

Each part answers a different question:

PartResponsibilityLifetime
ViewWhat UI should this build describe?Immutable configuration replaced during rebuilds.
ElementWhich existing UI identity and state does that description match?Retained while reconciliation preserves its identity.
RenderObjectWhat size, paint output and hit-test behavior does it produce?Retained and updated by its owning element.
LayerHow should painted output be composited?A fresh layer tree is built for each frame.
SemanticsWhat roles, properties and actions should accessibility expose?A separate tree alongside the visual pipeline.

A view that composes other views need not own a render object. Rebuilding a view, laying out a render object and repainting it are separate operations; a change can invalidate the work it needs without recreating the entire pipeline.

Read the concepts in order

From an interaction to a frame

An event callback changes state and requests the affected work. During build, views read state and describe children; reconciliation preserves matching elements. Layout passes constraints down and sizes up, then paint records output for composition. The engine consumes the scene and submits GPU work. The platform and scheduler arrange frames on demand.

Build, layout and paint run synchronously. Async work belongs at the IO and scheduling edges; its results enter UI work through the runtime’s delivery paths. Presentation capabilities such as focus and rebuild handles are acquired in lifecycle hooks, which receive LifecycleContext; build receives BuildContext for describing UI and reading dependencies.

For ownership, frame transactions and crate boundaries, continue with the architecture guide. The Flutter → FLUI mapping can help translate familiar vocabulary; FLUI’s contracts and Rust APIs determine the behavior here.

View, Element, RenderObject

Flutter counterpart: Widget, Element, RenderObject, Layer.

FLUI’s pipeline is four trees, each built from the last, with a fifth, the semantics tree, built alongside for accessibility:

View (config)  →  Element (lifecycle)  →  RenderObject (layout/paint)  →  Layer (compositing)

View

A view is an immutable, cheap-to-clone description of a piece of UI. An application writes two kinds:

  • a StatelessView, whose build(&self, ctx) returns the views it is made of;
  • a StatefulView with its ViewState: create_state(&self, ctx) makes the state once, when the view is first mounted, and the state’s build runs again whenever something it read changes.
#![allow(unused)]
fn main() {
use flui::prelude::*;

#[derive(Clone, StatelessView)]
struct Greeting {
    name: String,
}

impl StatelessView for Greeting {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Text::new(format!("Hello, {}!", self.name))
    }
}

#[derive(Clone, StatefulView)]
struct Counter;

struct CounterState {
    count: Signal<u32>,
}

impl StatefulView for Counter {
    type State = CounterState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> CounterState {
        CounterState { count: ctx.signal(0) }
    }
}

impl ViewState<Counter> for CounterState {
    fn build(&self, _view: &Counter, ctx: &dyn BuildContext) -> impl IntoView {
        let count = self.count;
        Column::new((
            Greeting { name: "FLUI".to_owned() },
            Text::new(count.get(ctx).to_string()),
            RawButton::new(Text::new("Increment"))
                .on_pressed(move |ctx| count.update(ctx, |n| *n += 1)),
        ))
    }
}
}

Element

An element is the mutable, long-lived counterpart of a view: it holds the view it was built from, its position in the tree, and its lifecycle state. Rebuilding the tree reconciles new views against existing elements by key and type, and reuses an element, with the state and render object it owns, wherever they match. Elements are the retained half, views the ephemeral half. An application never names an element type; it reaches its element through the ctx its hooks receive.

RenderObject

A render object performs layout, paint and hit testing. Two protocols ship: the box protocol (RenderBox, most widgets) and the sliver protocol (RenderSliver, scrollable and virtualized content). See Layout: constraints down, sizes up for the box protocol.

An element owns at most one render object. Views that only compose other views, like both views above, have none; only the leaf render-backed widgets do. See “Add a render object” in Extending FLUI for the checklist to implement a new one.

Layer

Paint records into layers: a closed set of kinds (pictures, clips, transforms, opacity, textures, platform views) that flui-engine composites and rasterizes. A layer is a value of one enum rather than an open trait hierarchy; crates/flui-layer/ARCHITECTURE.md has the reasoning.

Keys

Flutter counterpart: Key, ValueKey, ObjectKey, GlobalKey.

Keys control how the reconciler matches a new View against an existing Element when a parent rebuilds. Without one, matching falls back to position and type, which breaks state when a list of children is reordered or filtered.

The key types a view writes are at flui::view: ValueKey and two widget-layer keys; UniqueKey and the ViewKey trait every key implements are at flui::foundation. A view holds its key in a field marked #[view(key)], which the StatelessView and StatefulView derives read: the field is a key, an Option of one, or an Rc<dyn ViewKey> or Box<dyn ViewKey>.

#![allow(unused)]
fn main() {
use flui::prelude::*;
use flui::view::ValueKey;

#[derive(Clone, StatelessView)]
struct TodoRow {
    #[view(key)]
    key: ValueKey<u64>,
    title: String,
}

impl StatelessView for TodoRow {
    fn build(&self, _ctx: &dyn BuildContext) -> impl IntoView {
        Text::new(self.title.clone())
    }
}

let row = TodoRow { key: ValueKey::new(7), title: "Buy milk".to_owned() };
let _ = row;
}

The two widget-layer key types:

  • ObjectKey is keyed by a value’s identity, for reordering a list of items each backed by a distinct object.
  • GlobalKey<T> is unique across the whole tree and reaches an element’s state from outside the normal parent-to-child data flow. Use it sparingly: it breaks locality.
#![allow(unused)]
fn main() {
use std::rc::Rc;
use flui::view::{GlobalKey, ObjectKey};

struct Note { title: String }

let note = Rc::new(Note { title: "Groceries".to_owned() });
// Equal for the same `Rc`, different for another `Note` with the same title.
let row_key = ObjectKey::new(&note);
let _ = (row_key, &note.title);

// A key that will name one `NoteState` wherever it is mounted.
struct NoteState;
let editor_key: GlobalKey<NoteState> = GlobalKey::new();
// Outside a running application no element can hold it, so nothing is found.
assert_eq!(editor_key.with_current_state(|_state| ()), None);
}

Lifecycle

Every Element moves through a fixed set of lifecycle states, defined as enum Lifecycle in crates/flui-view/src/element/lifecycle.rs:

Initial → Active ⇄ Inactive → Defunct
  • Initial — created but not yet mounted into the tree.
  • Active — mounted, participating in builds, can be marked dirty, has valid parent/child relationships.
  • Inactive — temporarily removed from the tree; state is preserved and the Element may be reactivated within the same frame (its RenderObject, if any, is detached but not disposed).
  • Defunct — permanently removed; the Element will be dropped.

Platform/lifecycle-scoped capabilities — rebuild_handle(), post_frame_handle(), text_input_handle(), focus_manager() — are acquired only while an Element is transitioning through create_state/init_state/did_change_dependencies, never from inside build/perform_layout/paint. They live on LifecycleContext: BuildContext, which only those three hooks receive, so acquiring one in build is a compile error (ADR-0078). See View, Element, RenderObject for BuildContext itself.

Layout: constraints down, sizes up

Flutter counterpart: BoxConstraints, RenderBox.performLayout.

FLUI’s box layout protocol is “constraints go down, sizes go up, parent sets position”. A parent passes its child a BoxConstraints, the child picks its own Size within those constraints and returns it, and the parent then positions the child. A child never sees its parent’s size or position directly, and a parent never dictates an exact size without also allowing the child to choose within a range.

A size satisfies a BoxConstraints if and only if min_width <= width <= max_width and min_height <= height <= max_height. A parent derives its child’s constraints from its own: a Padding deflates them by its insets, so a tight window stays tight for its child, and a Center or an Align loosens them, so its child may pick any size up to the parent’s:

#![allow(unused)]
fn main() {
use flui::geometry::{EdgeInsets, Size};
use flui::rendering::BoxConstraints;

// The window gives the root a tight 400 × 300.
let window = BoxConstraints::tight(Size::new(400.0, 300.0));
assert!(window.is_satisfied_by(Size::new(400.0, 300.0)));

// A Padding takes 16 from each side: its child must be exactly the rest.
let padded = window.deflate(EdgeInsets::all(16.0));
assert_eq!(padded.biggest(), Size::new(368.0, 268.0));
assert_eq!(padded.smallest(), Size::new(368.0, 268.0));

// A Center inside it lets its child pick any size up to that.
let centered = padded.loosen();
assert_eq!(centered.smallest(), Size::new(0.0, 0.0));

// A child that asks for more than it may have gets the closest size that fits.
assert_eq!(centered.constrain(Size::new(500.0, 20.0)), Size::new(368.0, 20.0));
}

A render object implements the protocol in perform_layout: it lays out each child against the constraints it chooses for that child, positions the children, and returns its own size. Layout and child measurements return typed errors; propagate them with ?, since a rejected measurement supplies no size to position or paint. See ADR-0181 for ordinary text rejection and changed-input recovery, and Extending FLUI for writing a render object of your own.

For virtualized and scrollable content, RenderSliver implements a second, parallel protocol instead of the box protocol: see View, Element, RenderObject.

State: signals, InheritedView, ValueNotifier

Flutter counterpart: State.setState, InheritedWidget, ValueNotifier.

FLUI has three ways state enters the tree. Application and element-local state is a presentation-scoped signal; scope-wide data is an InheritedView; a controller that lives outside the tree is a ValueNotifier or another Listenable.

Signals

Signal<T> (ADR-0074) is a Copy handle to a value in the presentation’s reactive graph. A state creates its signals in create_state, so it is born with them; build reads them, which subscribes the element; an event callback writes them through the ctx it receives (ADR-0086):

#![allow(unused)]
fn main() {
use flui::prelude::*;

#[derive(Clone, StatefulView)]
struct Counter;

struct CounterState {
    count: Signal<u32>,
}

impl StatefulView for Counter {
    type State = CounterState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> CounterState {
        CounterState { count: ctx.signal(0) }
    }
}

impl ViewState<Counter> for CounterState {
    fn build(&self, _view: &Counter, ctx: &dyn BuildContext) -> impl IntoView {
        let count = self.count;
        RawButton::new(Text::new(format!("Pressed {} times", count.get(ctx))))
            .on_pressed(move |ctx| count.update(ctx, |n| *n += 1))
    }
}
}

build reads signals but never writes them: its BuildContext is not a context a write accepts, so a write there does not compile, and a write opened through a WriterSource while a build runs is refused at run time (SignalError::WrittenDuringBuild). A write rebuilds exactly the elements that read the signal. A widget that has to write from a callback with no ctx (one shaped Fn() or Fn(&str)) takes a WriterSource from ctx.writer_source() in create_state, keeps it in its state, and moves a clone into the callback, which writes through it: source.write(|ctx| count.set(ctx, 0)).

InheritedView

Data placed higher in the tree and read from below. A descendant reads it with ctx.depend_on::<T, _>(…), which also registers the dependency, and update_should_notify decides whether dependents rebuild when the data changes:

#![allow(unused)]
fn main() {
use flui::prelude::*;
use flui::view::{BoxedView, InheritedView, impl_inherited_view};

#[derive(Clone)]
struct Accent {
    color: Color,
    child: BoxedView,
}

impl InheritedView for Accent {
    type Data = Color;

    fn data(&self) -> &Color {
        &self.color
    }

    fn child(&self) -> &BoxedView {
        &self.child
    }

    fn update_should_notify(&self, old: &Self) -> bool {
        self.color != old.color
    }
}

impl_inherited_view!(Accent);

#[derive(Clone, StatelessView)]
struct Swatch;

impl StatelessView for Swatch {
    fn build(&self, ctx: &dyn BuildContext) -> impl IntoView {
        let color = ctx.depend_on::<Accent, _>(|accent| *accent.data()).unwrap_or(Color::BLACK);
        Text::new(format!("{color:?}"))
    }
}

let tree = Accent { color: Color::rgb(0, 120, 215), child: BoxedView::new(Swatch.into_view()) };
let _ = tree;
}

ValueNotifier

A ChangeNotifier that holds a single value and notifies its listeners when the value changes. It suits state observed from outside the view tree, or shared across more than one subtree without an InheritedView:

#![allow(unused)]
fn main() {
use std::cell::Cell;
use std::rc::Rc;
use flui::foundation::ValueNotifier;

let mut volume = ValueNotifier::new(50_u8);
let heard = Rc::new(Cell::new(0));
let seen = Rc::clone(&heard);
let _subscription = volume.listen(Rc::new(move || seen.set(seen.get() + 1)));

volume.set_value(60);
assert_eq!(*volume, 60);
assert_eq!(heard.get(), 1);
}

Flutter → FLUI mapping

A vocabulary table for readers coming from Flutter. Every row is checked against the real trait or struct in crates/.

FlutterFLUIWhere
StatelessWidgetStatelessView (#[derive(StatelessView)])crates/flui-view/src/view/stateless.rs
StatefulWidget + State<T>StatefulView + ViewState<V>crates/flui-view/src/view/stateful.rs
BuildContextBuildContext trait for build; the presentation capabilities (rebuild_handle(), post_frame_handle(), text_input_handle(), focus_manager(), …) live on its LifecycleContext subtrait, which only create_state/init_state/did_change_dependencies receive (ADR-0078)crates/flui-view/src/context/build_context.rs
setState(() => ...)A Signal<T> created with ctx.signal(..) in create_state, written through the ctx of an event callback; the signal rebuilds the elements that read itcrates/flui-view/src/reactive/, crates/flui-view/src/context/build_context.rs
InheritedWidgetInheritedViewcrates/flui-view/src/view/inherited.rs
NavigatorThe page stack inside a Router<R>; a page reaches its router with Router::of(ctx) (GoRouter.of(context)) and its own route with PageHandle::of(ctx) (ModalRoute.of(context)), and Route, PageRoute and PageTransitions shape how a page is presentedcrates/flui-widgets/src/navigator/
RouterRouter<R: Routable> + RouterHandle<R>, with #[derive(Routable)] on a route enumcrates/flui-widgets/src/router/
WidgetsAppWidgetsApp (WidgetsApp::new(home) or WidgetsApp::router(router))crates/flui-widgets/src/app/widgets_app.rs
MaterialApp / CupertinoAppMaterialApp / CupertinoApppackages/flui-material/src/app.rs, packages/flui-cupertino/src/app.rs
WidgetTester (testWidgets, pumpWidget, pump, pumpAndSettle, tap, enterText, sendKeyEvent)scenario::Tester (Tester::mount, replace_root, pump, pump_for, settle, tap, type_text, press_keys), synchronouscrates/flui-testing/src/scenario/tester.rs, crates/flui-testing/src/scenario/in_process.rs
tester.platformDispatcher (textScaleFactorTestValue, accessibilityFeaturesTestValue, …), tester.viewTester::platform on a headless tester (set_system_preferences, set_motion, set_window_focused, set_window_visible): each is heard at once, and the next pump builds what it changedcrates/flui-testing/src/scenario/platform.rs
find.text, find.byKey, find.bySemanticsLabelfind::text, find::id, find::button, find::role: each a Find over the semantics tree, naming one element (.all(), .first(), .nth(n) widen it)crates/flui-testing/src/scenario/find.rs, crates/flui-protocol/src/locator.rs
expect(finder, findsOneWidget)t.expect(&find, exists()) (gone(), count(n), name, checked(), enabled(), …)crates/flui-testing/src/scenario/matcher.rs

Notes

  • A test finds what a user perceives. flui::testing::scenario::find builds the same Find the driver and an agent use, resolved over the window’s semantics tree, so a test written against a headless scenario::Tester runs unchanged on a device. find.byType and find.byWidget have no counterpart: the semantics tree carries no widget types, and a type finder ties a test to how a screen is composed rather than to what it shows. A widget that publishes no semantics is found by the identifier its author gives a group around it (Semantics::new().container(true).role(SemanticsRole::Group).identifier(..)) and find::id. Actions wait for their input to land and their frame to run, and an expectation waits while the application has a frame or work due now, then fails at once with the window’s outline; nothing waits on a clock the test did not move with pump_for. An ambiguous Find fails with its candidates instead of tapping the first.
  • Router is the primary navigation API. Routes are values: a #[derive(Routable)] enum with one #[route("…")] pattern per variant, and a Router<R> that keeps the stack of route values, which a page pushes and pops through the RouterHandle<R> that Router::of(ctx) resolves in build, as GoRouter.of(context) does; the callback that navigates moves the handle, since it runs with no place in the tree (ADR-0330). Navigator is the Router’s internal page stack, not a second way to navigate; Flutter’s named routes (pushNamed, onGenerateRoute) have no counterpart, since a route is a typed value with a path. Dialogs, popups and menus are pageless popup routes a page pushes through its PageHandle (show_dialog(&page, …) for showDialog(context: …)): they never enter the URL or the stack a Router restores. A thread that needs to navigate writes a signal the page reacts to; there is no cross-thread navigation command.
  • MaterialApp is WidgetsApp plus theming. MaterialApp wraps a WidgetsApp, resolves ThemeMode against the platform brightness, publishes the resolved ThemeData through Theme, and installs a ScaffoldMessenger. run_app(MaterialApp::new(home)) is the usual root; Theme::new(ThemeData::light(), <root view>) passed to run_app still works for an app that wants only the theme.
  • Layer is a closed enum, not a class hierarchy — see View, Element, RenderObject.

State outside the table

Flutter has no built-in equivalent of FLUI’s presentation-scoped signals: Signal<T> (ADR-0074) is a Copy handle created with ctx.signal(value) in create_state, read in build, and written from an event callback. See State for it and the other ways state enters the tree.

Widget catalog

The framework crates are not yet published to crates.io (only the flui-cli tool is), so there is no docs.rs page for the widgets to link to yet — until there is, this page points at the source tree instead of listing every widget by name here (a hand-maintained list would go stale the moment a widget is added; the source directories do not). This page has no screenshots yet.

Controlled values: Slider and Disclosure

Slider and Disclosure report proposed values through on_changed; the parent decides whether to commit them. Their displayed and accessible state changes when the parent rebuilds with the new value. Without a callback, the control is disabled.

The view below keeps both values in signals its state is born with, reads them in build and writes them from the event callbacks, as in the first run counter:

#![allow(unused)]
fn main() {
use flui::prelude::*;

#[derive(Clone, StatefulView)]
struct SoundSettings;

struct SoundSettingsState {
    volume: Signal<f64>,
    expansion: Signal<ExpansionState>,
}

impl StatefulView for SoundSettings {
    type State = SoundSettingsState;

    fn create_state(&self, ctx: &dyn LifecycleContext) -> SoundSettingsState {
        SoundSettingsState {
            volume: ctx.signal(50.0),
            expansion: ctx.signal(ExpansionState::Collapsed),
        }
    }
}

impl ViewState<SoundSettings> for SoundSettingsState {
    fn build(&self, _view: &SoundSettings, ctx: &dyn BuildContext) -> impl IntoView {
        let volume = self.volume;
        let expansion = self.expansion;
        let range = match NumericRange::try_new(volume.get(ctx), 0.0, 100.0, 5.0) {
            Ok(range) => range,
            Err(error) => return Text::new(format!("Invalid volume range: {error}")).boxed(),
        };

        Column::new((
            Semantics::new().label("Volume").child(
                Slider::new(range).on_changed(move |ctx, proposed| volume.set(ctx, proposed)),
            ),
            Disclosure::new(
                expansion.get(ctx),
                Text::new("Details"),
                Text::new("Additional settings"),
            )
            .on_changed(move |ctx, proposed| expansion.set(ctx, proposed)),
        ))
        .boxed()
    }
}
}

NumericRange::try_new(value, min, max, step) returns a Result: every argument must be finite, the bounds must admit the current value, and step must be positive. The step governs keyboard and increment/decrement proposals; an admitted exact numeric value from an assistive setter is not rounded to a step boundary. A zero-span range is valid but inert for adjustments.

Give Disclosure a passive header such as Text; Disclosure owns header activation. Collapsing unmounts the body, removing its layout, input, focus and accessibility contributions. It does not guarantee retention of child-local state; keep data that must survive collapse in the parent. See Lifecycle for ownership.

Source, by crate

  • flui-widgets — the core, theme-independent catalog: layout (flex, stack, wrap, clip, physical model), scrolling, text, images, icons, animation/transitions, overlays, navigation, and the app-level container/app scaffolding. crates/flui-widgets/src/
  • flui-material — Material Design widgets (buttons, app bar, scaffold, cards, dialogs, navigation, form controls) built on flui-widgets plus ColorScheme/ThemeData, an official package on flui-sdk. packages/flui-material/src/
  • flui-cupertino — iOS-style widgets (buttons, nav bar, page/tab scaffold, theming) built on flui-widgets plus CupertinoTheme, an official package on flui-sdk. packages/flui-cupertino/src/

Once the framework crates publish, this page becomes a thin index into docs.rs instead of the source tree directly.

Cookbook

Choose a recipe by the behavior you want to add.

TaskRecipe
Validate editable text and show an errorForms
Load data and display loading, error, and retry statesAsync
Share colors and styling through the view treeThemes
Animate a value over timeAnimation
Exercise a view without opening a windowTesting

For typed navigation, root an app in MaterialApp::router (or WidgetsApp::router) over a #[derive(Routable)] route enum; its pages push and pop route values through a RouterHandle (ADR-0330; see the mapping notes).

Forms

A form is a validated TextField with an inline error, and a Submit button that only enables once the field is valid.

For the headless test pattern that exercises a form without a window, see docs/testing.md, and Testing for the equivalent on the counter example.

Async

FLUI’s frame scheduler (flui-scheduler) paces async work that interacts with the frame and rebuild cycle, rather than tokio running it detached. Loading state, an error-with-Retry path and cancellation when a route is popped mid-fetch are each built on that scheduler.

Themes

An application wraps its root view in a theme, then calls run_app: Theme::new(ThemeData::light(), ...) for Material, CupertinoTheme for Cupertino. An application that also wants light/dark switching, a navigator and a ScaffoldMessenger roots itself in MaterialApp (packages/flui-material/src/app.rs) instead, which resolves ThemeMode and publishes the ThemeData through Theme itself; see the Flutter → FLUI mapping notes.

Animation

flui-widgets’s animated/ and transitions/ modules (crates/flui-widgets/src/animated/, crates/flui-widgets/src/transitions/) are the widget-level entry points most application code reaches for. They sit on the animation engine in flui-animation.

Testing

Flutter counterpart: WidgetTester, find, testWidgets.

Enable flui’s testing feature in your development dependency and write a test the way a user uses the screen: find what they see, act on it, expect what they should see next.

#![allow(unused)]
fn main() {
use flui::prelude::*;
use flui::testing::scenario::matcher::exists;
use flui::testing::scenario::{Tester, find};

#[derive(Clone, StatefulView)]
struct CounterView;
struct CounterState { count: Signal<usize> }
impl StatefulView for CounterView {
    type State = CounterState;
    fn create_state(&self, ctx: &dyn LifecycleContext) -> CounterState {
        CounterState { count: ctx.signal(0) }
    }
}
impl ViewState<CounterView> for CounterState {
    fn build(&self, _view: &CounterView, ctx: &dyn BuildContext) -> impl IntoView {
        let count = self.count;
        Column::new((
            Text::new(count.get(ctx).to_string()),
            RawButton::new(Text::new("Increment"))
                .on_pressed(move |ctx| count.update(ctx, |n| *n += 1)),
        ))
    }
}
// In an application this is the body of a `#[test] fn counter_increments()`.
let mut t = Tester::mount(CounterView);
t.expect(&find::text("0"), exists());
t.tap(&find::button("Increment"));
t.expect(&find::text("1"), exists());
t.finish();
}

The view under test is a counter like the one in View, Element, RenderObject, with a labelled button; its definition is hidden here.

Tester::mount mounts the view as run_app does, with the runtime’s root scopes, in an 800 by 600 window on a manual clock (Tester::mount_in with a TestWindow built to a WindowSpec for another size, scale, platform or safe area). find builds the same Finds the driver and an agent use, over the semantics tree, so the test reads what a screen reader reads. A tap lands at the centre of the element’s visible part through the window’s own input path, after the tester checked it is visible, enabled and not covered; it returns once the frame after the input ran. An expectation waits while the application has a frame or work due now, and fails at once, listing what the window shows, when the application is idle: advance the clock yourself with pump_for to reach a timer. A Find names exactly one element and a second match fails the step; .all() with count(n) counts them, and exists(), gone(), name, value, checked(), enabled() and focused() are the matchers. finish ends the test with its end checks: the application settled, unmounted, nothing left running.

A failure names what was looked for and what the window showed instead. A widget that publishes no semantics is found by the identifier you give a group around it, Semantics::new().container(true).role(SemanticsRole::Group).identifier(..), and find::id.

flui::testing::rendering tests a render object of your own without widgets. The test tiers map the framework’s own test pyramid.

Architecture

FLUI has two maps: the tree pipeline explains how UI becomes a frame, and the workspace tiers explain which crates may depend on which. Start with the concept overview for the trees, then use this page to find the design records behind a particular subsystem.

The architectural source lives in the repository’s own documentation. Crate manifests declare the dependency rules, which a change is read against before it merges; CI’s checks job checks repository documentation links with lychee. These checks do not establish that every described behavior is implemented. For a decision’s implementation and migration state, read its status and the architecture file of the owning crate.

Start here

  • docs/architecture.md — the pipeline overview (View → Element → RenderObject → Layer → flui-engine → wgpu).
  • docs/adr/ — the cross-crate decisions the code follows, one file per decision.
  • AGENTS.md — the design stance and the rules the compiler and gates enforce.
  • docs/crates.md — crate responsibilities and the dependency map.

Follow a subsystem

QuestionDesign recordImplementation guide
Who owns UI state, and how does work cross threads?ADR-0027: owner-affine UI runtimes, ADR-0171: UI runtime and host vocabularyRuntime architecture
What is one frame, and where is a failed presentation contained?ADR-0048: frame transaction boundary, ADR-0083: frame runtimeRuntime architecture
Why are capabilities acquired outside build?ADR-0078: rules in types and lintsView architecture, lifecycle
Where do platform contracts end and OS backends begin?ADR-0082: platform contract cratePlatform API architecture
How do paint commands become a composited scene?Pipeline overviewRendering architecture, layer architecture, engine architecture
How are text measurement, carets and painted glyphs related?ADR-0092: per-runtime text over ParleyPainting architecture
How do official packages use the framework?ADR-0088: packages, SDK and facadeSDK architecture

Use the implementation guide to find the invariants and named tests for a decision. A record may describe a migration with only some moves landed; the presence of an ADR is not a promise that its whole target is available through the public API.

Per-crate architecture

Most crates carry their own crates/<crate>/ARCHITECTURE.md for the design decisions local to it, including a ## Mapping decisions section recording those decisions.

Architecture Decision Records

Protocol-level decisions — ones that change a contract more than one crate depends on — are recorded as ADRs under docs/adr/. Browse the directory by filename (ADR-NNNN-<slug>.md) or search the repository for the number cited by the code or comment you’re reading. Read the record’s Status first, then follow its related decisions and migration notes. An ADR that revises an earlier one carries an explicit Supersedes:/Superseded-by: pair — see AGENTS.md’s ADR Policy.