build method

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

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

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). 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 and from the given BuildContext.

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. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  // LayoutBuilder provides constraints required for item sizing calculation.
  return LayoutBuilder(builder: (context, constraints) {
    // A padding calculation variable that resolves null
    // to a temporary zero value. The original null padding
    // must be preserved for the [BoxScrollView] to calculate
    // an effective padding with SafeArea. Create a
    // temporary variable here to avoid overwriting null.
    EdgeInsets paddingHolder = padding as EdgeInsets? ?? EdgeInsets.zero;
    // The maximum number of items that can fit on one row.
    int crossAxisCount;
    // The maximum number of items that fit under the max row count.
    int? maxItemCount;
    // Manual padding adjustment for alignment.
    EdgeInsetsGeometry alignmentPadding;
    // The width of all items and padding.
    double crossAxisWidth;
    // The maximum width available for items.
    double crossAxisExtent = constraints.maxWidth - paddingHolder.horizontal;
    assert(crossAxisExtent > 0,
        '$paddingHolder exceeds layout width (${constraints.maxWidth})');
    // Switch between grid delegate behavior.
    if (gridDelegate.crossAxisExtent != null) {
      // Fixed item size.
      crossAxisCount = (crossAxisExtent /
              (gridDelegate.crossAxisExtent! + gridDelegate.crossAxisSpacing))
          .floor();
      crossAxisWidth = crossAxisCount *
              (gridDelegate.crossAxisExtent! +
                  gridDelegate.crossAxisSpacing) +
          paddingHolder.horizontal;
    } else if (gridDelegate.maxCrossAxisExtent != null) {
      // Max item size.
      crossAxisCount = (crossAxisExtent /
              (gridDelegate.maxCrossAxisExtent! +
                  gridDelegate.crossAxisSpacing))
          .ceil();
      final double usableCrossAxisExtent = crossAxisExtent -
          gridDelegate.crossAxisSpacing * (crossAxisCount - 1);
      final double childCrossAxisExtent =
          usableCrossAxisExtent / crossAxisCount;
      crossAxisWidth = crossAxisCount *
              (childCrossAxisExtent + gridDelegate.crossAxisSpacing) +
          paddingHolder.horizontal;
    } else {
      // Min item size.
      crossAxisCount = (crossAxisExtent /
              (gridDelegate.minCrossAxisExtent! +
                  gridDelegate.crossAxisSpacing))
          .floor();
      final double usableCrossAxisExtent = crossAxisExtent -
          gridDelegate.crossAxisSpacing * (crossAxisCount - 1);
      final double childCrossAxisExtent =
          usableCrossAxisExtent / crossAxisCount;
      crossAxisWidth = crossAxisCount *
              (childCrossAxisExtent + gridDelegate.crossAxisSpacing) +
          paddingHolder.horizontal;
    }
    // Calculate padding adjustment for alignment.
    if (alignment == Alignment.centerLeft ||
        alignment == Alignment.topLeft ||
        alignment == Alignment.bottomLeft) {
      // Align left, no padding.
      alignmentPadding = const EdgeInsets.only(left: 0);
    } else if (alignment == Alignment.center ||
        alignment == Alignment.topCenter ||
        alignment == Alignment.bottomCenter) {
      // Align center, divide remaining space between left and right
      // after subtracting last item spacing padding.
      double paddingCalc = constraints.maxWidth - crossAxisWidth;
      if (paddingCalc <= 0) {
        // There is no additional space. No padding.
        alignmentPadding = const EdgeInsets.only(left: 0);
      } else if (paddingCalc > gridDelegate.crossAxisSpacing) {
        // There is enough room to center items correctly.
        // Add padding equivalent to the last item to the first item.
        // Then split the remaining space.
        alignmentPadding = EdgeInsets.only(
            left: ((constraints.maxWidth -
                        crossAxisWidth -
                        gridDelegate.crossAxisSpacing) /
                    2) +
                gridDelegate.crossAxisSpacing);
      } else {
        // There is not enough space to correctly center items.
        // Add all remaining space to left padding.
        alignmentPadding = EdgeInsets.only(left: paddingCalc);
      }
    } else {
      // Align right, add all remaining space to left padding.
      alignmentPadding =
          EdgeInsets.only(left: constraints.maxWidth - crossAxisWidth);
    }
    // Force row limit by calculating item limit.
    if (maxRowCount != null) {
      maxItemCount = maxRowCount! * crossAxisCount;
    }
    // Internal children builder delegate.
    SliverChildDelegate childrenDelegate = SliverChildBuilderDelegate(
        itemBuilder,
        childCount: maxItemCount ?? itemCount,
        addAutomaticKeepAlives: addAutomaticKeepAlives,
        addRepaintBoundaries: addRepaintBoundaries,
        addSemanticIndexes: addSemanticIndexes);
    return Container(
      padding: alignmentPadding,
      child: _ResponsiveGridViewLayout(
        scrollDirection: scrollDirection,
        reverse: reverse,
        controller: controller,
        primary: primary,
        physics: physics,
        shrinkWrap: shrinkWrap,
        padding: padding,
        gridDelegate: gridDelegate,
        childrenDelegate: childrenDelegate,
        itemCount: itemCount,
        cacheExtent: cacheExtent,
        semanticChildCount: semanticChildCount,
        dragStartBehavior: dragStartBehavior,
        keyboardDismissBehavior: keyboardDismissBehavior,
        clipBehavior: clipBehavior,
        restorationId: restorationId,
      ),
    );
  });
}