build method

  1. @override
Widget build (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:

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 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:

Implementation

@override
Widget build(BuildContext context) {
  // TODO(ianh): This whole build function doesn't handle RTL yet.
  assert(debugCheckHasMaterialLocalizations(context));
  final ThemeData themeData = Theme.of(context);
  final MaterialLocalizations localizations = MaterialLocalizations.of(context);
  // HEADER
  final List<Widget> headerWidgets = <Widget>[];
  double startPadding = 24.0;
  if (_selectedRowCount == 0) {
    headerWidgets.add(Expanded(child: widget.header));
    if (widget.header is ButtonBar) {
      // We adjust the padding when a button bar is present, because the
      // ButtonBar introduces 2 pixels of outside padding, plus 2 pixels
      // around each button on each side, and the button itself will have 8
      // pixels internally on each side, yet we want the left edge of the
      // inside of the button to line up with the 24.0 left inset.
      // TODO(ianh): Better magic. See https://github.com/flutter/flutter/issues/4460
      startPadding = 12.0;
    }
  } else {
    headerWidgets.add(Expanded(
      child: Text(localizations.selectedRowCountTitle(_selectedRowCount)),
    ));
  }
  if (widget.actions != null) {
    headerWidgets.addAll(
      widget.actions.map<Widget>((Widget action) {
        return Padding(
          // 8.0 is the default padding of an icon button
          padding: const EdgeInsetsDirectional.only(start: 24.0 - 8.0 * 2.0),
          child: action,
        );
      }).toList()
    );
  }

  // FOOTER
  final TextStyle footerTextStyle = themeData.textTheme.caption;
  final List<Widget> footerWidgets = <Widget>[];
  if (widget.onRowsPerPageChanged != null) {
    final List<Widget> availableRowsPerPage = widget.availableRowsPerPage
      .where((int value) => value <= _rowCount || value == widget.rowsPerPage)
      .map<DropdownMenuItem<int>>((int value) {
        return DropdownMenuItem<int>(
          value: value,
          child: Text('$value')
        );
      })
      .toList();
    footerWidgets.addAll(<Widget>[
      Container(width: 14.0), // to match trailing padding in case we overflow and end up scrolling
      Text(localizations.rowsPerPageTitle),
      ConstrainedBox(
        constraints: const BoxConstraints(minWidth: 64.0), // 40.0 for the text, 24.0 for the icon
        child: Align(
          alignment: AlignmentDirectional.centerEnd,
          child: DropdownButtonHideUnderline(
            child: DropdownButton<int>(
              items: availableRowsPerPage,
              value: widget.rowsPerPage,
              onChanged: widget.onRowsPerPageChanged,
              style: footerTextStyle,
              iconSize: 24.0,
            ),
          ),
        ),
      ),
    ]);
  }
  footerWidgets.addAll(<Widget>[
    Container(width: 32.0),
    Text(
      localizations.pageRowsInfoTitle(
        _firstRowIndex + 1,
        _firstRowIndex + widget.rowsPerPage,
        _rowCount,
        _rowCountApproximate
      )
    ),
    Container(width: 32.0),
    IconButton(
      icon: const Icon(Icons.chevron_left),
      padding: EdgeInsets.zero,
      tooltip: localizations.previousPageTooltip,
      onPressed: _firstRowIndex <= 0 ? null : _handlePrevious
    ),
    Container(width: 24.0),
    IconButton(
      icon: const Icon(Icons.chevron_right),
      padding: EdgeInsets.zero,
      tooltip: localizations.nextPageTooltip,
      onPressed: (!_rowCountApproximate && (_firstRowIndex + widget.rowsPerPage >= _rowCount)) ? null : _handleNext
    ),
    Container(width: 14.0),
  ]);

  // CARD
  return Card(
    semanticContainer: false,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Semantics(
          container: true,
          child: DefaultTextStyle(
            // These typographic styles aren't quite the regular ones. We pick the closest ones from the regular
            // list and then tweak them appropriately.
            // See https://material.google.com/components/data-tables.html#data-tables-tables-within-cards
            style: _selectedRowCount > 0 ? themeData.textTheme.subhead.copyWith(color: themeData.accentColor)
                                         : themeData.textTheme.title.copyWith(fontWeight: FontWeight.w400),
            child: IconTheme.merge(
              data: const IconThemeData(
                opacity: 0.54
              ),
              child: ButtonTheme.bar(
                child: Ink(
                  height: 64.0,
                  color: _selectedRowCount > 0 ? themeData.secondaryHeaderColor : null,
                  child: Padding(
                    padding: EdgeInsetsDirectional.only(start: startPadding, end: 14.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: headerWidgets
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: DataTable(
            key: _tableKey,
            columns: widget.columns,
            sortColumnIndex: widget.sortColumnIndex,
            sortAscending: widget.sortAscending,
            onSelectAll: widget.onSelectAll,
            rows: _getRows(_firstRowIndex, widget.rowsPerPage)
          )
        ),
        DefaultTextStyle(
          style: footerTextStyle,
          child: IconTheme.merge(
            data: const IconThemeData(
              opacity: 0.54
            ),
            child: Container(
              height: 56.0,
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                reverse: true,
                child: Row(
                  children: footerWidgets,
                ),
              ),
            ),
          ),
        ),
      ],
    ),
  );
}