Element type is a generic widget wrapper that allows you to build composable user interfaces without leaking implementation details in your view logic.
Type Signature
Type Parameters
The lifetime of the element
The message type produced by user interactions
The theme type used for styling
The renderer type used for drawing
Creating Elements
new
Creates a newElement containing the given widget.
Into<Element>, so you can often convert them directly:
Accessing the Widget
as_widget
Returns a reference to the widget contained in the element.as_widget_mut
Returns a mutable reference to the widget contained in the element.Message Transformation
map
Applies a transformation to the produced message of the element. This is useful for building composable UIs where different components produce different message types.A function that transforms messages of type
Message into messages of type Bcounter::Message, but you want to display multiple counters. You can use map to compose them:
Debugging
explain
Marks the element as “to-be-explained”. The renderer will draw the layout bounds graphically, which is very useful for debugging layout issues.The color to use for drawing the layout bounds
Converting from Option
You can convertOption<T> where T: Into<Element> directly into an Element. If the option is None, an empty element with zero size will be created:
Key Concepts
Type Erasure
Element uses trait objects (Box<dyn Widget>) to erase the concrete widget type. This allows you to:
- Return different widget types from the same function
- Store heterogeneous widgets in collections
- Build flexible and composable UIs
Composition
Element enables true component composition in Iced. Each component can:
- Define its own message type
- Manage its own state
- Be reused independently
- Transform messages to integrate with parent components
