Iced is inspired by The Elm Architecture, which requires splitting your user interface into four distinct, interacting concepts:
- State: The data representing the current condition of your application.
- Messages: An enumeration of user interactions or meaningful events (e.g., button clicks).
- View logic: A function that transforms your State into a layout of widgets. These widgets are configured to produce Messages when interacted with.
- Update logic: A function that receives Messages and modifies the State accordingly.
When you run an Iced application, the runtime handles the lifecycle: it executes the view logic to layout widgets, processes system events to produce messages, and triggers the update logic to keep the state in sync with the UI.
// 1. State
struct Counter {
value: i32,
}
// 2. Messages
enum Message {
Increment,
Decrement,
}
// 3. View logic
impl Counter {
pub fn view(&self) -> Column<'_, Message> {
column![
button("+").on_press(Message::Increment),
text(self.value).size(50),
button("-").on_press(Message::Decrement),
]
}
// 4. Update logic
pub fn update(&mut self, message: Message) {
match message {
Message::Increment => self.value += 1,
Message::Decrement => self.value -= 1,
}
}
}
// Execution
fn main() -> iced::Result {
iced::run("A cool counter", Counter::update, Counter::view)
}