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) {
  var sw = Stopwatch();
  sw.start();
  // assert(!_debugInteractive || debugCheckHasMaterial(context));
  assert(debugCheckHasMaterial(context));

  final theme = Theme.of(context);
  final effectiveHeadingRowColor =
      headingRowColor ?? theme.dataTableTheme.headingRowColor;
  final effectiveDataRowColor =
      dataRowColor ?? theme.dataTableTheme.dataRowColor;
  final defaultRowColor = WidgetStateProperty.resolveWith(
    (Set<WidgetState> states) {
      if (states.contains(WidgetState.selected)) {
        return theme.colorScheme.primary.withOpacity(0.08);
      }
      return null;
    },
  );
  final anyRowSelectable =
      rows.any((m.DataRow row) => row.onSelectChanged != null);
  final displayCheckboxColumn = showCheckboxColumn && anyRowSelectable;
  final rowsWithCheckbox = displayCheckboxColumn
      ? rows.where((m.DataRow row) => row.onSelectChanged != null)
      : <DataRow>[];
  final rowsChecked = rowsWithCheckbox.where((m.DataRow row) => row.selected);
  final allChecked =
      displayCheckboxColumn && rowsChecked.length == rowsWithCheckbox.length;
  final anyChecked = displayCheckboxColumn && rowsChecked.isNotEmpty;
  final someChecked = anyChecked && !allChecked;
  final effectiveHorizontalMargin = horizontalMargin ??
      theme.dataTableTheme.horizontalMargin ??
      _horizontalMargin;
  final effectiveColumnSpacing =
      columnSpacing ?? theme.dataTableTheme.columnSpacing ?? _columnSpacing;

  final double effectiveHeadingRowHeight = headingRowHeight ??
      theme.dataTableTheme.headingRowHeight ??
      _headingRowHeight;

  final tableColumnWidths = List<TableColumnWidth>.filled(
      columns.length + (displayCheckboxColumn ? 1 : 0),
      const _NullTableColumnWidth());

  final headingRow = _buildHeadingRow(
      context, theme, effectiveHeadingRowColor, tableColumnWidths.length);

  final actualFixedRows =
      math.max(0, rows.isEmpty ? 0 : math.min(fixedTopRows, rows.length + 1));
  final actualFixedColumns = math.max(
      0,
      rows.isEmpty
          ? 0
          : math.min(fixedLeftColumns,
              columns.length + (showCheckboxColumn ? 1 : 0)));

  List<TableRow>? coreRows = rows.isEmpty ||
          actualFixedColumns >= columns.length + (showCheckboxColumn ? 1 : 0)
      ? null
      : _buildTableRows(
          anyRowSelectable,
          effectiveDataRowColor,
          context,
          theme,
          tableColumnWidths.length - actualFixedColumns,
          defaultRowColor,
          actualFixedRows == 0
              ? _buildHeadingRow(context, theme, effectiveHeadingRowColor,
                  tableColumnWidths.length - actualFixedColumns)
              : null,
          actualFixedRows > 0 ? actualFixedRows - 1 : 0);

  List<TableRow>? fixedColumnsRows = rows.isEmpty
      ? null
      : actualFixedColumns > 0
          ? (actualFixedRows < 1
              ? [
                  _buildHeadingRow(
                      context,
                      theme,
                      fixedColumnsColor != null
                          ? WidgetStatePropertyAll(fixedColumnsColor)
                          : effectiveHeadingRowColor,
                      actualFixedColumns),
                  ..._buildTableRows(
                      anyRowSelectable,
                      fixedColumnsColor != null
                          ? WidgetStatePropertyAll(fixedColumnsColor)
                          : effectiveDataRowColor,
                      context,
                      theme,
                      actualFixedColumns,
                      defaultRowColor,
                      null,
                      0,
                      0,
                      true)
                ]
              : _buildTableRows(
                  anyRowSelectable,
                  fixedColumnsColor != null
                      ? WidgetStatePropertyAll(fixedColumnsColor)
                      : effectiveDataRowColor,
                  context,
                  theme,
                  actualFixedColumns,
                  defaultRowColor,
                  null,
                  actualFixedRows - 1,
                  0,
                  true))
          : null;

  List<TableRow>? fixedRows = actualFixedRows > 0
      ? (actualFixedRows == 1
          ? [
              _buildHeadingRow(
                  context,
                  theme,
                  headingRowColor ?? effectiveHeadingRowColor,
                  tableColumnWidths.length - actualFixedColumns)
            ]
          : [
              _buildHeadingRow(
                  context,
                  theme,
                  headingRowColor ?? effectiveHeadingRowColor,
                  tableColumnWidths.length - actualFixedColumns),
              ..._buildTableRows(
                  anyRowSelectable,
                  headingRowColor ?? effectiveDataRowColor,
                  context,
                  theme,
                  tableColumnWidths.length - actualFixedColumns,
                  defaultRowColor,
                  null,
                  0,
                  actualFixedRows - 1,
                  true)
            ])
      : null;

  List<TableRow>? fixedCornerRows =
      actualFixedColumns > 0 && actualFixedRows > 0
          ? (actualFixedRows == 1
              ? [
                  _buildHeadingRow(
                      context,
                      theme,
                      fixedCornerColor != null
                          ? WidgetStatePropertyAll(fixedCornerColor)
                          : effectiveHeadingRowColor,
                      actualFixedColumns)
                ]
              : [
                  _buildHeadingRow(
                      context,
                      theme,
                      fixedCornerColor != null
                          ? WidgetStatePropertyAll(fixedCornerColor)
                          : effectiveHeadingRowColor,
                      actualFixedColumns),
                  ..._buildTableRows(
                      anyRowSelectable,
                      fixedCornerColor != null
                          ? WidgetStatePropertyAll(fixedCornerColor)
                          : effectiveDataRowColor,
                      context,
                      theme,
                      actualFixedColumns,
                      defaultRowColor,
                      null,
                      0,
                      actualFixedRows - 1,
                      true)
                ])
          : null;

  double checkBoxWidth = _addCheckBoxes(
      displayCheckboxColumn,
      effectiveHorizontalMargin,
      tableColumnWidths,
      headingRow,
      effectiveHeadingRowHeight,
      context,
      someChecked,
      allChecked,
      coreRows,
      fixedRows,
      fixedCornerRows,
      fixedColumnsRows,
      rows,
      actualFixedRows,
      effectiveDataRowColor);

  var builder = LayoutBuilder(builder: (context, constraints) {
    return SyncedScrollControllers(
        scrollController: scrollController,
        sc12toSc11Position: true,
        horizontalScrollController: horizontalScrollController,
        sc22toSc21Position: true,
        builder: (context, sc11, sc12, sc21, sc22) {
          var coreVerticalController = sc11;
          var leftColumnVerticalContoller = sc12;
          var coreHorizontalController = sc21;
          var fixedRowsHorizontalController = sc22;

          var displayColumnIndex = 0;

          // size & build checkboxes in heading and leftmost column
          // to be substracted from total width available to columns

          if (checkBoxWidth > 0) displayColumnIndex += 1;

          // size data columns
          final widths = _calculateDataColumnSizes(
              constraints, checkBoxWidth, effectiveHorizontalMargin);

          // File empty cells in created rows with actual widgets
          for (int dataColumnIndex = 0;
              dataColumnIndex < columns.length;
              dataColumnIndex++) {
            final m.DataColumn column = columns[dataColumnIndex];

            final double paddingStart;
            if (dataColumnIndex == 0 && displayCheckboxColumn) {
              paddingStart = effectiveHorizontalMargin / 2.0;
            } else if (dataColumnIndex == 0 && !displayCheckboxColumn) {
              paddingStart = effectiveHorizontalMargin;
            } else {
              paddingStart = effectiveColumnSpacing / 2.0;
            }

            final double paddingEnd;
            if (dataColumnIndex == columns.length - 1) {
              paddingEnd = effectiveHorizontalMargin;
            } else {
              paddingEnd = effectiveColumnSpacing / 2.0;
            }

            final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
              start: paddingStart,
              end: paddingEnd,
            );

            tableColumnWidths[displayColumnIndex] =
                FixedColumnWidth(widths[dataColumnIndex]);

            var h = _buildHeadingCell(
                context: context,
                padding: padding,
                effectiveHeadingRowHeight: effectiveHeadingRowHeight,
                label: column.label,
                tooltip: column.tooltip,
                numeric: column.numeric,
                onSort: column.onSort != null
                    ? () => column.onSort!(dataColumnIndex,
                        sortColumnIndex != dataColumnIndex || !sortAscending)
                    : null,
                sorted: dataColumnIndex == sortColumnIndex,
                ascending: sortAscending,
                overlayColor: effectiveHeadingRowColor);

            headingRow.children[displayColumnIndex] =
                h; // heading row alone is used to display table header should there be no data rows

            if (displayColumnIndex < actualFixedColumns) {
              if (actualFixedRows < 1) {
                fixedColumnsRows![0].children[displayColumnIndex] = h;
              } else if (actualFixedRows > 0) {
                fixedCornerRows![0].children[displayColumnIndex] = h;
              }
            } else {
              if (actualFixedRows < 1 && coreRows != null) {
                coreRows[0]
                    .children[displayColumnIndex - actualFixedColumns] = h;
              } else if (actualFixedRows > 0) {
                fixedRows![0]
                    .children[displayColumnIndex - actualFixedColumns] = h;
              }
            }

            var rowIndex = 0;
            var skipRows = actualFixedRows == 1
                ? 0
                : actualFixedRows > 1
                    ? actualFixedRows - 1
                    : -1;

            for (final m.DataRow row in rows) {
              final DataCell cell = row.cells[dataColumnIndex];

              var c = _buildDataCell(
                  context: context,
                  padding: padding,
                  specificRowHeight:
                      row is DataRow ? row.specificRowHeight : null,
                  label: cell.child,
                  numeric: column.numeric,
                  placeholder: cell.placeholder,
                  showEditIcon: cell.showEditIcon,
                  onTap: cell.onTap,
                  onDoubleTap: cell.onDoubleTap,
                  onLongPress: cell.onLongPress,
                  onTapDown: cell.onTapDown,
                  onTapCancel: cell.onTapCancel,
                  onRowTap: row is DataRow ? row.onTap : null,
                  onRowDoubleTap: row is DataRow ? row.onDoubleTap : null,
                  onRowLongPress: row.onLongPress,
                  onRowSecondaryTap:
                      row is DataRow ? row.onSecondaryTap : null,
                  onRowSecondaryTapDown:
                      row is DataRow ? row.onSecondaryTapDown : null,
                  onSelectChanged: row.onSelectChanged != null
                      ? () => row.onSelectChanged!(!row.selected)
                      : null,
                  overlayColor: row.color ?? effectiveDataRowColor);

              if (displayColumnIndex < actualFixedColumns) {
                if (rowIndex + 1 < actualFixedRows) {
                  fixedCornerRows![rowIndex + 1]
                      .children[displayColumnIndex] = c;
                } else {
                  fixedColumnsRows![rowIndex - skipRows]
                      .children[displayColumnIndex] = c;
                }
              } else {
                if (rowIndex + 1 < actualFixedRows) {
                  fixedRows![rowIndex + 1]
                      .children[displayColumnIndex - actualFixedColumns] = c;
                } else {
                  coreRows![rowIndex - skipRows]
                      .children[displayColumnIndex - actualFixedColumns] = c;
                }
              }

              rowIndex += 1;
            }
            displayColumnIndex += 1;
          }

          var widthsAsMap = tableColumnWidths.asMap();
          Map<int, TableColumnWidth>? leftWidthsAsMap = actualFixedColumns > 0
              ? tableColumnWidths.take(actualFixedColumns).toList().asMap()
              : null;
          Map<int, TableColumnWidth>? rightWidthsAsMap = actualFixedColumns >
                  0
              ? tableColumnWidths.skip(actualFixedColumns).toList().asMap()
              : null;

          bool isRowsEmpty(List<TableRow>? rows) {
            return rows == null || rows.isEmpty || rows[0].children.isEmpty;
          }

          var coreTable = Table(
              columnWidths:
                  actualFixedColumns > 0 ? rightWidthsAsMap : widthsAsMap,
              children: coreRows ?? [],
              border: border == null
                  ? null
                  : isRowsEmpty(fixedRows) && isRowsEmpty(fixedColumnsRows)
                      ? border
                      : !isRowsEmpty(fixedRows) &&
                              !isRowsEmpty(fixedColumnsRows)
                          ? TableBorder(
                              //top: border!.top,
                              //left: border!.left,
                              right: border!.right,
                              bottom: border!.bottom,
                              verticalInside: border!.verticalInside,
                              horizontalInside: border!.horizontalInside,
                              borderRadius: border!.borderRadius)
                          : isRowsEmpty(fixedRows)
                              ? TableBorder(
                                  top: border!.top,
                                  //left: border!.left,
                                  right: border!.right,
                                  bottom: border!.bottom,
                                  verticalInside: border!.verticalInside,
                                  horizontalInside: border!.horizontalInside,
                                  borderRadius: border!.borderRadius)
                              : TableBorder(
                                  //top: border!.top,
                                  left: border!.left,
                                  right: border!.right,
                                  bottom: border!.bottom,
                                  verticalInside: border!.verticalInside,
                                  horizontalInside: border!.horizontalInside,
                                  borderRadius: border!.borderRadius));

          Table? fixedRowsTabel;
          Table? fixedColumnsTable;
          Table? fixedTopLeftCornerTable;
          Widget? fixedColumnAndCornerCol;
          Widget? fixedRowsAndCoreCol;

          if (rows.isNotEmpty) {
            if (fixedRows != null &&
                !isRowsEmpty(fixedRows) &&
                actualFixedColumns <
                    columns.length + (showCheckboxColumn ? 1 : 0)) {
              fixedRowsTabel = Table(
                  columnWidths:
                      actualFixedColumns > 0 ? rightWidthsAsMap : widthsAsMap,
                  children: fixedRows,
                  border: border == null
                      ? null
                      : isRowsEmpty(fixedCornerRows)
                          ? border
                          : TableBorder(
                              top: border!.top,
                              //left: border!.left,
                              right: border!.right,
                              bottom: border!.bottom,
                              verticalInside: border!.verticalInside,
                              horizontalInside: border!.horizontalInside,
                              borderRadius: border!.borderRadius));
            }

            if (fixedColumnsRows != null && !isRowsEmpty(fixedColumnsRows)) {
              fixedColumnsTable = Table(
                  columnWidths: leftWidthsAsMap,
                  children: fixedColumnsRows,
                  border: border == null
                      ? null
                      : isRowsEmpty(fixedCornerRows)
                          ? border
                          : TableBorder(
                              //top: border!.top,
                              left: border!.left,
                              right: border!.right,
                              bottom: border!.bottom,
                              verticalInside: border!.verticalInside,
                              horizontalInside: border!.horizontalInside,
                              borderRadius: border!.borderRadius));
            }

            if (fixedCornerRows != null && !isRowsEmpty(fixedCornerRows)) {
              fixedTopLeftCornerTable = Table(
                  columnWidths: leftWidthsAsMap,
                  children: fixedCornerRows,
                  border: border);
            }

            Widget addBottomMargin(Table t) =>
                bottomMargin != null && bottomMargin! > 0
                    ? Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [t, SizedBox(height: bottomMargin!)])
                    : t;

            var scrollBarTheme = Theme.of(context).scrollbarTheme;
            // flutter/lib/src/material/scrollbar.dart, scrollbar decides whther to create  Cupertino or Material scrollbar, Cupertino ignores themes
            var isiOS = Theme.of(context).platform == TargetPlatform.iOS;

            // For iOS/Cupertino scrollbar
            fixedRowsAndCoreCol = Scrollbar(
                thumbVisibility: false,
                trackVisibility: false,
                thickness: 0,
                controller: coreHorizontalController,
                child: Stack(children: [
                  Scrollbar(
                      thumbVisibility: false,
                      trackVisibility: false,
                      thickness: 0,
                      controller: coreVerticalController,
                      child: SingleChildScrollView(
                          controller: coreVerticalController,
                          scrollDirection: Axis.vertical,
                          child: SingleChildScrollView(
                              controller: coreHorizontalController,
                              scrollDirection: Axis.horizontal,
                              child: a.PaddingTop(
                                  padding: effectiveHeadingRowHeight,
                                  child: addBottomMargin(coreTable))))),
                  ScrollConfiguration(
                      behavior: ScrollConfiguration.of(context)
                          .copyWith(scrollbars: false),
                      child: Scrollbar(
                          thumbVisibility: false,
                          trackVisibility: false,
                          thickness: 0,
                          child: SingleChildScrollView(
                              controller: fixedRowsHorizontalController,
                              scrollDirection: Axis.horizontal,
                              child: (fixedRowsTabel != null)
                                  ? a.SurfaceCard(
                                      borderRadius: a.BorderRadius.zero,
                                      padding: EdgeInsets.zero,
                                      borderWidth: 0,
                                      borderColor: Colors.transparent,
                                      surfaceOpacity: 0.1,
                                      child: fixedRowsTabel,
                                    )
                                  // WOrkaround for a bug when there's no horizontal scrollbar should there be no this SingleChildScrollView. I.e. originally this part was ommited and not scrollable was added to the column if not fixed top row was visible
                                  : SizedBox(
                                      height: 0,
                                      width: widths.fold<double>(
                                          0,
                                          (previousValue, value) =>
                                              previousValue + value),
                                    ))))
                ]));

            fixedColumnAndCornerCol = fixedTopLeftCornerTable == null &&
                    fixedColumnsTable == null
                ? null
                : Column(mainAxisSize: MainAxisSize.min, children: [
                    if (fixedTopLeftCornerTable != null)
                      fixedTopLeftCornerTable,
                    if (fixedColumnsTable != null)
                      Flexible(
                          fit: FlexFit.loose,
                          child: ScrollConfiguration(
                              behavior: ScrollConfiguration.of(context)
                                  .copyWith(scrollbars: false),
                              child: SingleChildScrollView(
                                  controller: leftColumnVerticalContoller,
                                  scrollDirection: Axis.vertical,
                                  child: addBottomMargin(fixedColumnsTable))))
                  ]);
          }

          var completeWidget = Container(
              decoration: decoration ?? theme.dataTableTheme.decoration,
              child: Material(
                  type: MaterialType.transparency,
                  borderRadius: border?.borderRadius,
                  clipBehavior: clipBehavior,
                  child: rows.isEmpty
                      ? Column(children: [
                          SingleChildScrollView(
                              controller: coreHorizontalController,
                              scrollDirection: Axis.horizontal,
                              child: Table(
                                  columnWidths: widthsAsMap,
                                  border: border,
                                  children: [headingRow])),
                          Flexible(
                              fit: FlexFit.tight,
                              child: empty ?? const SizedBox())
                        ])
                      : Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (fixedColumnAndCornerCol != null)
                              fixedColumnAndCornerCol,
                            if (fixedRowsAndCoreCol != null)
                              Flexible(
                                  fit: FlexFit.tight,
                                  child: fixedRowsAndCoreCol)
                          ],
                        )));

          return completeWidget;
        });
  });

  sw.stop();

  if (dataTableShowLogs && kDebugMode) {
    debugPrint('DataTable2 built: ${sw.elapsedMilliseconds}ms');
  }

  return builder;
}