build method Null safety

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

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:

class MyButton extends StatefulWidget {
  ...
  final Color color;

  @override
  Widget build(BuildContext context, MyButtonState state) {
    ... () { 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.

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 MyButtonState extends State<MyButton> {
  ...
  @override
  Widget build(BuildContext context) {
    ... () { 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) {
  assert(debugCheckHasMediaQuery(context));
  assert(debugCheckHasDirectionality(context));
  final MediaQueryData mediaQuery = MediaQuery.of(context);
  final ThemeData themeData = Theme.of(context);
  final TextDirection textDirection = Directionality.of(context);

  // TODO(Piinks): Remove old SnackBar API after migrating ScaffoldMessenger
  _accessibleNavigation = mediaQuery.accessibleNavigation;
  if (_snackBars.isNotEmpty) {
    final ModalRoute<dynamic>? route = ModalRoute.of(context);
    if (route == null || route.isCurrent) {
      if (_snackBarController!.isCompleted && _snackBarTimer == null) {
        final SnackBar snackBar = _snackBars.first._widget;
        _snackBarTimer = Timer(snackBar.duration, () {
          assert(
            _snackBarController!.status == AnimationStatus.forward ||
              _snackBarController!.status == AnimationStatus.completed,
          );
          // Look up MediaQuery again in case the setting changed.
          final MediaQueryData mediaQuery = MediaQuery.of(context);
          if (mediaQuery.accessibleNavigation && snackBar.action != null)
            return;
          hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
        });
      }
    } else {
      _snackBarTimer?.cancel();
      _snackBarTimer = null;
    }
  }

  final List<LayoutId> children = <LayoutId>[];
  _addIfNonNull(
    children,
    widget.body == null ? null : _BodyBuilder(
      extendBody: widget.extendBody,
      extendBodyBehindAppBar: widget.extendBodyBehindAppBar,
      body: widget.body!,
    ),
    _ScaffoldSlot.body,
    removeLeftPadding: false,
    removeTopPadding: widget.appBar != null,
    removeRightPadding: false,
    removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
    removeBottomInset: _resizeToAvoidBottomInset,
  );
  if (_showBodyScrim) {
    _addIfNonNull(
      children,
      ModalBarrier(
        dismissible: false,
        color: _bodyScrimColor,
      ),
      _ScaffoldSlot.bodyScrim,
      removeLeftPadding: true,
      removeTopPadding: true,
      removeRightPadding: true,
      removeBottomPadding: true,
    );
  }

  if (widget.appBar != null) {
    final double topPadding = widget.primary ? mediaQuery.padding.top : 0.0;
    _appBarMaxHeight = AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) + topPadding;
    assert(_appBarMaxHeight! >= 0.0 && _appBarMaxHeight!.isFinite);
    _addIfNonNull(
      children,
      ConstrainedBox(
        constraints: BoxConstraints(maxHeight: _appBarMaxHeight!),
        child: FlexibleSpaceBar.createSettings(
          currentExtent: _appBarMaxHeight!,
          child: widget.appBar!,
        ),
      ),
      _ScaffoldSlot.appBar,
      removeLeftPadding: false,
      removeTopPadding: false,
      removeRightPadding: false,
      removeBottomPadding: true,
    );
  }

  bool isSnackBarFloating = false;
  double? snackBarWidth;
  // We should only be using one API for SnackBars. Currently, we can use the
  // Scaffold, which creates a SnackBar queue (_snackBars), or the
  // ScaffoldMessenger, which sends a SnackBar to descendant Scaffolds.
  // (_messengerSnackBar).
  assert(
    _snackBars.isEmpty || _messengerSnackBar == null,
    'Only one API should be used to manage SnackBars. The ScaffoldMessenger is '
    'the preferred API instead of the Scaffold methods.',
  );

  if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) {
    final Widget stack = Stack(
      alignment: Alignment.bottomCenter,
      children: <Widget>[
        ..._dismissedBottomSheets,
        if (_currentBottomSheet != null) _currentBottomSheet!._widget,
      ],
    );
    _addIfNonNull(
      children,
      stack,
      _ScaffoldSlot.bottomSheet,
      removeLeftPadding: false,
      removeTopPadding: true,
      removeRightPadding: false,
      removeBottomPadding: _resizeToAvoidBottomInset,
    );
  }

  // SnackBar set by ScaffoldMessenger
  if (_messengerSnackBar != null) {
    final SnackBarBehavior snackBarBehavior = _messengerSnackBar?._widget.behavior
      ?? themeData.snackBarTheme.behavior
      ?? SnackBarBehavior.fixed;
    isSnackBarFloating = snackBarBehavior == SnackBarBehavior.floating;
    snackBarWidth = _messengerSnackBar?._widget.width;

    _addIfNonNull(
      children,
      _messengerSnackBar?._widget,
      _ScaffoldSlot.snackBar,
      removeLeftPadding: false,
      removeTopPadding: true,
      removeRightPadding: false,
      removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
      maintainBottomViewPadding: !_resizeToAvoidBottomInset,
    );
  }

  // SnackBar set by Scaffold
  // TODO(Piinks): Remove old SnackBar API after migrating ScaffoldMessenger
  if (_snackBars.isNotEmpty) {
    final SnackBarBehavior snackBarBehavior = _snackBars.first._widget.behavior
      ?? themeData.snackBarTheme.behavior
      ?? SnackBarBehavior.fixed;
    isSnackBarFloating = snackBarBehavior == SnackBarBehavior.floating;
    snackBarWidth = _snackBars.first._widget.width;

    _addIfNonNull(
      children,
      _snackBars.first._widget,
      _ScaffoldSlot.snackBar,
      removeLeftPadding: false,
      removeTopPadding: true,
      removeRightPadding: false,
      removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
      maintainBottomViewPadding: !_resizeToAvoidBottomInset,
    );
  }

  // MaterialBanner set by ScaffoldMessenger
  if (_messengerMaterialBanner != null) {
    _addIfNonNull(
      children,
      _messengerMaterialBanner?._widget,
      _ScaffoldSlot.materialBanner,
      removeLeftPadding: false,
      removeTopPadding: widget.appBar != null,
      removeRightPadding: false,
      removeBottomPadding: true,
      maintainBottomViewPadding: !_resizeToAvoidBottomInset,
    );
  }

  if (widget.persistentFooterButtons != null) {
    _addIfNonNull(
      children,
      Container(
        decoration: BoxDecoration(
          border: Border(
            top: Divider.createBorderSide(context, width: 1.0),
          ),
        ),
        child: SafeArea(
          top: false,
          child: IntrinsicHeight(
            child: Container(
              alignment: AlignmentDirectional.centerEnd,
              padding: const EdgeInsets.all(8),
              child: OverflowBar(
                spacing: 8,
                overflowAlignment: OverflowBarAlignment.end,
                children: widget.persistentFooterButtons!,
              ),
            ),
          ),
        ),
      ),
      _ScaffoldSlot.persistentFooter,
      removeLeftPadding: false,
      removeTopPadding: true,
      removeRightPadding: false,
      removeBottomPadding: false,
      maintainBottomViewPadding: !_resizeToAvoidBottomInset,
    );
  }

  if (widget.bottomNavigationBar != null) {
    _addIfNonNull(
      children,
      widget.bottomNavigationBar,
      _ScaffoldSlot.bottomNavigationBar,
      removeLeftPadding: false,
      removeTopPadding: true,
      removeRightPadding: false,
      removeBottomPadding: false,
      maintainBottomViewPadding: !_resizeToAvoidBottomInset,
    );
  }

  _addIfNonNull(
    children,
    _FloatingActionButtonTransition(
      fabMoveAnimation: _floatingActionButtonMoveController,
      fabMotionAnimator: _floatingActionButtonAnimator,
      geometryNotifier: _geometryNotifier,
      currentController: _floatingActionButtonVisibilityController,
      child: widget.floatingActionButton,
    ),
    _ScaffoldSlot.floatingActionButton,
    removeLeftPadding: true,
    removeTopPadding: true,
    removeRightPadding: true,
    removeBottomPadding: true,
  );

  switch (themeData.platform) {
    case TargetPlatform.iOS:
    case TargetPlatform.macOS:
      _addIfNonNull(
        children,
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: _handleStatusBarTap,
          // iOS accessibility automatically adds scroll-to-top to the clock in the status bar
          excludeFromSemantics: true,
        ),
        _ScaffoldSlot.statusBar,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
        removeBottomPadding: true,
      );
      break;
    case TargetPlatform.android:
    case TargetPlatform.fuchsia:
    case TargetPlatform.linux:
    case TargetPlatform.windows:
      break;
  }

  if (_endDrawerOpened.value) {
    _buildDrawer(children, textDirection);
    _buildEndDrawer(children, textDirection);
  } else {
    _buildEndDrawer(children, textDirection);
    _buildDrawer(children, textDirection);
  }

  // The minimum insets for contents of the Scaffold to keep visible.
  final EdgeInsets minInsets = mediaQuery.padding.copyWith(
    bottom: _resizeToAvoidBottomInset ? mediaQuery.viewInsets.bottom : 0.0,
  );

  // The minimum viewPadding for interactive elements positioned by the
  // Scaffold to keep within safe interactive areas.
  final EdgeInsets minViewPadding = mediaQuery.viewPadding.copyWith(
    bottom: _resizeToAvoidBottomInset &&  mediaQuery.viewInsets.bottom != 0.0 ? 0.0 : null,
  );

  // extendBody locked when keyboard is open
  final bool _extendBody = minInsets.bottom <= 0 && widget.extendBody;

  return _ScaffoldScope(
    hasDrawer: hasDrawer,
    geometryNotifier: _geometryNotifier,
    child: ScrollNotificationObserver(
      child: Material(
        color: widget.backgroundColor ?? themeData.scaffoldBackgroundColor,
        child: AnimatedBuilder(animation: _floatingActionButtonMoveController, builder: (BuildContext context, Widget? child) {
          return CustomMultiChildLayout(
            delegate: _ScaffoldLayout(
              extendBody: _extendBody,
              extendBodyBehindAppBar: widget.extendBodyBehindAppBar,
              minInsets: minInsets,
              minViewPadding: minViewPadding,
              currentFloatingActionButtonLocation: _floatingActionButtonLocation!,
              floatingActionButtonMoveAnimationProgress: _floatingActionButtonMoveController.value,
              floatingActionButtonMotionAnimator: _floatingActionButtonAnimator,
              geometryNotifier: _geometryNotifier,
              previousFloatingActionButtonLocation: _previousFloatingActionButtonLocation!,
              textDirection: textDirection,
              isSnackBarFloating: isSnackBarFloating,
              snackBarWidth: snackBarWidth,
            ),
            children: children,
          );
        }),
      ),
    ),
  );
}