build method

  1. @override
Widget build(
  1. BuildContext context
)
inherited

Describes the part of the user interface represented by this widget.

The framework calls this method in a number of different situations. For example:

This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor, the given BuildContext, and the internal state of this State object.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.

Design discussion

Why is the build method on State, and not StatefulWidget?

Putting a Widget build(BuildContext context) method on State rather than putting a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when subclassing StatefulWidget.

For example, AnimatedWidget is a subclass of StatefulWidget that introduces an abstract Widget build(BuildContext context) method for its subclasses to implement. If StatefulWidget already had a build method that took a State argument, AnimatedWidget would be forced to provide its State object to subclasses even though its State object is an internal implementation detail of AnimatedWidget.

Conceptually, StatelessWidget could also be implemented as a subclass of StatefulWidget in a similar manner. If the build method were on StatefulWidget rather than State, that would not be possible anymore.

Putting the build function on State rather than StatefulWidget also helps avoid a category of bugs related to closures implicitly capturing this. If you defined a closure in a build function on a StatefulWidget, that closure would implicitly capture this, which is the current widget instance, and would have the (immutable) fields of that instance in scope:

// (this is not valid Flutter code)
class MyButton extends StatefulWidgetX {
  MyButton({super.key, required this.color});

  final Color color;

  @override
  Widget build(BuildContext context, State state) {
    return SpecialWidget(
      handler: () { print('color: $color'); },
    );
  }
}

For example, suppose the parent builds MyButton with color being blue, the $color in the print function refers to blue, as expected. Now, suppose the parent rebuilds MyButton with green. The closure created by the first build still implicitly refers to the original widget and the $color still prints blue even through the widget has been updated to green; should that closure outlive its widget, it would print outdated information.

In contrast, with the build function on the State object, closures created during build implicitly capture the State instance instead of the widget instance:

class MyButton extends StatefulWidget {
  const MyButton({super.key, this.color = Colors.teal});

  final Color color;
  // ...
}

class MyButtonState extends State<MyButton> {
  // ...
  @override
  Widget build(BuildContext context) {
    return SpecialWidget(
      handler: () { print('color: ${widget.color}'); },
    );
  }
}

Now when the parent rebuilds MyButton with green, the closure created by the first build still refers to State object, which is preserved across rebuilds, but the framework has updated that State object's widget property to refer to the new MyButton instance and ${widget.color} prints green, as expected.

See also:

  • StatefulWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  resolveStylesIfUnresolved(context);

  Widget rtn = buildWidget(context);

  // inject base attributes
  if (widget.controller is WidgetController) {
    WidgetController widgetController = widget.controller as WidgetController;

    // Add KeyedSubtree with ValueKey based on testId to make widget findable in tests using find.byKey()
    if (widgetController.testId != null &&
        widgetController.testId!.isNotEmpty) {
      rtn = KeyedSubtree(
        key: ValueKey(widgetController.testId!),
        child: rtn,
      );
    }

    if (widgetController.textDirection != null) {
      rtn = Directionality(
          textDirection: widgetController.textDirection!, child: rtn);
    }

    if (widgetController.elevation != null) {
      rtn = Material(
          elevation: widgetController.elevation?.toDouble() ?? 0,
          shadowColor: widgetController.elevationShadowColor,
          borderRadius: widgetController.elevationBorderRadius?.getValue(),
          child: rtn);
    }

    // add tooltip handling if tooltip message is specified
    if (widgetController.toolTip != null) {
      rtn = Utils.getTooltipWidget(
        context,
        rtn,
        widgetController.toolTip,
        widgetController
      );
    }

    // in Web, capture the pointer if overlay on htmlelementview like Maps
    if (widgetController.captureWebPointer == true) {
      rtn = PointerInterceptor(child: rtn);
    }

    // wrap inside Align if specified
    if (widgetController.alignment != null) {
      rtn = Align(alignment: widgetController.alignment!, child: rtn);
    }

    // handle visibility
    if (widgetController.visibilityTransitionDuration != null) {
      rtn = AnimatedOpacity(
          // If visible, apply opacity if specified, else default to 1
          opacity: widgetController.visible != false
              ? (Utils.optionalDouble(widgetController.opacity ?? 1, min: 0, max: 1.0) ?? 1)
              : 0,
          duration: widgetController.visibilityTransitionDuration!,
          child: rtn);
    }
    // only wrap around Visibility if visible flag is specified,
    // since we don't want this on all widgets unnecessary
    else if (widgetController.visible != null) {
      rtn = Visibility(visible: widgetController.visible!, child: rtn);
    }

    // Handle standalone opacity
    // Apply only if visibilityTransitionDuration is NOT set (to avoid double wrapping)
    if (widgetController.visibilityTransitionDuration == null &&
        widgetController.opacity != null) {
      rtn = Opacity(
        opacity: Utils.optionalDouble(widgetController.opacity!, min: 0, max: 1.0) ?? 1.0,
        child: rtn,
      );
    }

    // Note that Positioned or expanded below has to be used directly inside
    // Stack and FlexBox, respectively. They should be the last widget returned.
    if (widgetController.hasPositions()) {
      if (StudioDebugger().debugMode) {
        rtn = StudioDebugger().assertHasStackWrapper(rtn, context);
      }
      rtn = Positioned(
          top: widgetController.stackPositionTop?.toDouble(),
          bottom: widgetController.stackPositionBottom?.toDouble(),
          left: widgetController.stackPositionLeft?.toDouble(),
          right: widgetController.stackPositionRight?.toDouble(),
          child: rtn);
    } else if (widgetController.flex != null ||
        widgetController.flexMode != null) {
      rtn = StudioDebugger().assertHasFlexBoxParent(context, rtn);

      if (widgetController.flexMode == null ||
          widgetController.flexMode == FlexMode.expanded) {
        rtn = Expanded(flex: widgetController.flex ?? 1, child: rtn);
      } else if (widgetController.flexMode == FlexMode.flexible) {
        rtn = Flexible(flex: widgetController.flex ?? 1, child: rtn);
      }
      // don't do anything for FlexMode.none
    } else if (widgetController.expanded == true) {
      if (StudioDebugger().debugMode) {
        rtn = StudioDebugger().assertHasColumnRowFlexWrapper(rtn, context);
      }

      /// Important notes:
      /// 1. If the Column/Row is scrollable, putting Expanded on the child will cause layout exception
      /// 2. If Column/Row is inside a parent without height/width constraint, it will collapse its size.
      ///    So if we put Expanded on the Column's child, layout exception will occur
      rtn = Expanded(child: rtn);
    }

    final isTestMode = EnvConfig().isTestMode;

    if (isTestMode &&
        widgetController.testId != null &&
        widgetController.testId!.isNotEmpty) {
      rtn = Semantics(
        //identifier: 'ID#${widgetController.testId!}',//can't use it till we move to flutter 3.19
        identifier: '${widgetController.testId!}: ',
        child: rtn,
      );
    }

    // If semantics is provided, use it. Otherwise, if label exists on the controller, use it as label for aria-label.
    final String? semanticsLabel = widgetController.getSemanticsLabel();
    final semantics = widgetController.semantics;

    if (semanticsLabel != null && semanticsLabel.isNotEmpty) {
      final flags = computeRoleFlags(rtn, semantics?.role);

      rtn = Semantics(
        label: semanticsLabel,
        hint: semantics?.hint,
        focusable: semantics?.focusable,
        button: flags.button,
        header: flags.header,
        image: flags.image,
        textField: flags.textField,
        checked: flags.checked,
        toggled: flags.toggled,
        enabled: flags.enabled,
        readOnly: flags.readOnly,
        obscured: flags.obscured,
        multiline: flags.multiline,
        selected: flags.selected,
        inMutuallyExclusiveGroup: flags.inMutuallyExclusiveGroup,
        child: semantics?.focusable == true
            ? FocusTraversalGroup(
                policy: ReadingOrderTraversalPolicy(),
                child: FocusableActionDetector(
                  enabled: true,
                  child: rtn,
                ),
              )
            : rtn,
      );
    }
  }
  return rtn;
}