Skip to content

Building Widgets

George Atkinson edited this page Jan 3, 2021 · 3 revisions

The first step to creating a user interface is adding the widgets that make it up. The following code demonstrates how to add a widget, in this case a button, as a child to an already existing parent.

let my_widget = Checkbox::new().with_icon_checked("\u{2713}").build(state, parent, |builder| builder);

Setting local data

Some widgets contain 'local' data which can only be accessed by the widget during building and event handling. Local data must be set on the widget instance before calling the build(...) function, as this will move the widget into the application state. In the example above, the with_icon_checked() function sets the icon, using a unicode character from the Entypo font, which is local data that lives within the widget.

This local data can then be accessed by the 'on_build()function within theBuildHanldertrait implementation, or by theon_event()andon_draw()functions within theEventHandler` trait implementation.

Building a widget

After creating the widget instance, it must be added to the application using the build(...) function. This calls the on_build(...) function of the widget and then moves the widget instance into the application state.

The build function takes 3 parameters, the state, the parent entity ID, and a closure which provides a builder. A builder encapsulates both the state and entity ID of the newly created widget and provides a way of setting inline styles properties.

The BuildHandler trait

All widgets implement the BuildHandler trait, which provides an on_build(...) function which is called when a widget is built.

The on_build() function has 3 parameters, a mutable reference to the widget instance for accessing local data, a mutable reference to the state, and the entity ID of the widget. These arguments can be used to set local data, set state data, build widgets, and send events.

The BuildHandler trait has an associated type called Ret which is the return type for the on_build function. Usually, this return type is Entity, which is then returned by the build() function of a widget and used to pass to other widgets as the parent entity ID. However, in some cases the return type is a tuple of Entity, e.g. (Entity, Entity). This is useful for container widgets which are made up of multiple sub-widgets, both of which can be parents to other widgets that you might add to them. For example, a tab bar header and tab bar container.

let (tab_bar, tab_container) = TabContainer::new().build(state, body, |builder| builder);

In the above example, calling build() on a TabContainer returns two entity ID's, one for the tab bar and one for the container.

Contents

Widgets

  • Checkbox
Clone this wiki locally