concept widget in category flutter

appears as: widgets, widgets, A widget, widget, widget, The widget, The widgets
Flutter in Action

This is an excerpt from Manning's book Flutter in Action.

Widgets have a few different life-cycle methods and object members. The most important method, though, is build(). The build() method must exist in every Flutter widget. This is the method in which you actually describe your view by returning widgets.

In Flutter, (nearly) everything is a widget, and widgets are just Dart classes that know how to describe their view. They’re blueprints that Flutter will use to paint elements on the screen. The widget class is the only view model that Flutter knows about. There aren’t separate controllers or views.

Listing 3.2. A widget with configuration
class SubmitButton extends StatelessWidget {
  final String buttonText;                    #1
  SubmitButton(this.buttonText);              #2

  Widget build(context) {
    return Button(
      child: Text(buttonText);                #3
    );
  }
}
Figure 3.17. The relationship between an element and a widget

It’s helpful for me if I consider the element the brains of the operation. Elements are simple in that they only contain meta information and a reference to a widget, but they also know how to update their own reference to a different widget if the widget changes.

Anytime Flutter is rebuilding, the element’s reference points to the new widget in the exact location in the widget tree of the element’s old reference. When Flutter is deciding what to rebuild and re-render after build is called, an element is going to look at the widget in the exact same place as the previous widget it referenced (see figure 3.18). Then, it’ll decide if the widget is the same (in which case it doesn’t need to do anything), or if the widget has changed, or it’s a different widget altogether (in which case it needs to re-render).

Figure 3.18. Each element points to a different widget and knows its type.

So, when you swap those two buttons, they replace each other in the widget tree, but the element’s reference points to the same location. Each element is going to look at its widget and say, “Has this widget changed? Or is it a new widget altogether?” So, we’d expect the element to see that the widget’s color property has changed, so it should in fact update its reference to the new widget.

  • In Flutter, everything is a widget, and widgets are just Dart classes that know how to describe their view.
  • A widget can define any aspect of an application’s view. Some widgets, such as Row, define aspects of layout. Some are less abstract and define structural elements, like Button and TextField.
  • sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest