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 ThemeData theme = Theme.of(context);
  final MaterialStateProperty<Color?>? effectiveHeadingRowColor =
      headingRowColor ?? theme.dataTableTheme.headingRowColor;
  final MaterialStateProperty<Color?>? effectiveDataRowColor =
      dataRowColor ?? theme.dataTableTheme.dataRowColor;
  final MaterialStateProperty<Color?> defaultRowColor =
      MaterialStateProperty.resolveWith(
    (Set<MaterialState> states) {
      if (states.contains(MaterialState.selected))
        return theme.colorScheme.primary.withOpacity(0.08);
      return null;
    },
  );
  final bool anyRowSelectable =
      rows.any((DataRow row) => row.onSelectChanged != null);
  final bool displayCheckboxColumn = showCheckboxColumn && anyRowSelectable;
  final Iterable<DataRow> rowsWithCheckbox = displayCheckboxColumn
      ? rows.where((DataRow row) => row.onSelectChanged != null)
      : <DataRowPlus>[];
  final Iterable<DataRow> rowsChecked =
      rowsWithCheckbox.where((DataRow row) => row.selected);
  final bool allChecked =
      displayCheckboxColumn && rowsChecked.length == rowsWithCheckbox.length;
  final bool anyChecked = displayCheckboxColumn && rowsChecked.isNotEmpty;
  final bool someChecked = anyChecked && !allChecked;
  final double effectiveHorizontalMargin = horizontalMargin ??
      theme.dataTableTheme.horizontalMargin ??
      _horizontalMargin;
  final double effectiveColumnSpacing =
      columnSpacing ?? theme.dataTableTheme.columnSpacing ?? _columnSpacing;
  final ThemeData themeData = Theme.of(context);
  final double effectiveCheckboxHorizontalMarginStart =
      checkboxHorizontalMargin ??
          themeData.dataTableTheme.checkboxHorizontalMargin ??
          effectiveHorizontalMargin;
  final double effectiveCheckboxHorizontalMarginEnd =
      checkboxHorizontalMargin ??
          themeData.dataTableTheme.checkboxHorizontalMargin ??
          effectiveHorizontalMargin / 2.0;

  late List<TableColumnWidth> effectiveTableColumns = [];
  List.generate(columns.length + (displayCheckboxColumn ? 1 : 0), (index) {
    if (tableColumnsWidth != null && tableColumnsWidth![index] != null) {
      effectiveTableColumns.add(tableColumnsWidth![index]!);
    } else {
      effectiveTableColumns.add(const _NullTableColumnWidth());
    }
  });
  List<TableRow> tableRows = [];
  bool useDefaultHeader = true;

  /// Add custom lines pre-header
  if (customRows != null) {
    customRows!.forEach((element) {
      if (element.index < 0 ||
          (element.index == 0 &&
              element.typeCustomRow == TypeCustomRow.REPLACE)) {
        tableRows.add(TableRow(
            children:
                List<Widget>.generate(effectiveTableColumns.length, (index) {
          if (index == 0 && displayCheckboxColumn) {
            return SizedBox();
          }
          return const _NullWidget();
        })));
      }
      if (element.index == 0 &&
          element.typeCustomRow == TypeCustomRow.REPLACE) {
        /// Header
        useDefaultHeader = false;
      }
    });
  }

  int currentQtdCustomLines = 0;
  for (int rowIndex = 0;
      rowIndex <

          /// Add +1 Header
          (rows.length + (useDefaultHeader ? 1 : 0)) +
              (customRows
                      ?.where((element) =>
                          element.index > 0 &&
                          element.typeCustomRow == TypeCustomRow.ADD)
                      .length ??
                  0);
      rowIndex++) {
    int indexCustomRow =
        customRows?.indexWhere((element) => element.index == rowIndex) ?? -1;
    if (indexCustomRow > -1) {
      tableRows.add(TableRow(
          key: customRows![indexCustomRow].key,
          children:
              List<Widget>.generate(effectiveTableColumns.length, (index) {
            if (index == 0 && displayCheckboxColumn) {
              return SizedBox();
            }
            return const _NullWidget();
          })));
      if (customRows![indexCustomRow].typeCustomRow ==
          TypeCustomRow.REPLACE) {
        continue;
      } else {
        //currentQtdCustomLines++;
      }
    }
    int index = rowIndex - (currentQtdCustomLines) - 1;
    if (index == -1) {
      /// Header

      final Color? resolvedHeadingRowColor =
          effectiveHeadingRowColor?.resolve(<MaterialState>{});
      final Color? rowColor = resolvedHeadingRowColor;

      final BorderSide borderSide = Divider.createBorderSide(
        context,
        width: dividerThickness ??
            theme.dataTableTheme.dividerThickness ??
            _dividerThickness,
      );
      final Border? border =
          showBottomBorder ? Border(bottom: borderSide) : null;

      tableRows.add(
        TableRow(
            key: _headingRowKey,
            decoration: BoxDecoration(
              border: border,
              color: rowColor,
            ),
            children: List<Widget>.filled(
                effectiveTableColumns.length, const _NullWidget())),
      );
    } else if (index < rows.length) {
      final bool isSelected = rows[index].selected;
      final bool isDisabled =
          anyRowSelectable && rows[index].onSelectChanged == null;
      final Set<MaterialState> states = <MaterialState>{
        if (isSelected) MaterialState.selected,
        if (isDisabled) MaterialState.disabled,
      };
      final Color? resolvedDataRowColor =
          (rows[index].color ?? effectiveDataRowColor)?.resolve(states);

      final Color? rowColor = resolvedDataRowColor;
      final BorderSide borderSide = Divider.createBorderSide(
        context,
        width: dividerThickness ??
            theme.dataTableTheme.dividerThickness ??
            _dividerThickness,
      );
      final Border? border = showBottomBorder
          ? Border(bottom: borderSide)
          : index == 0
              ? null
              : Border(top: borderSide);

      tableRows.add(
        TableRow(
            key: rows[index].key,
            decoration: BoxDecoration(
              border: border,
              color: rowColor ?? defaultRowColor.resolve(states),
            ),
            children: List<Widget>.filled(
                effectiveTableColumns.length, const _NullWidget())),
      );
      if (displayCheckboxColumn) {
        tableRows.last.children![0] = _buildCheckbox(
          context: context,
          checked: rows[index].selected,
          onRowTap: () =>
              rows[index].onSelectChanged?.call(!rows[index].selected),
          onCheckboxChanged: rows[index].onSelectChanged,
          overlayColor: rows[index].color ?? effectiveDataRowColor,
          tristate: false,
        );
      }
    }
  }

  int rowIndex;

  int displayColumnIndex = 0;
  if (displayCheckboxColumn) {
    effectiveTableColumns[0] = FixedColumnWidth(
        effectiveCheckboxHorizontalMarginStart +
            Checkbox.width +
            effectiveCheckboxHorizontalMarginEnd);
    int headerIndex = 0;
    if (customRows != null) {
      headerIndex = customRows!
          .where((element) =>
              element.index <= 0 &&
              element.typeCustomRow == TypeCustomRow.ADD)
          .length;
    }
    if (showCheckboxSelectAll) {
      tableRows[headerIndex].children![0] = _buildCheckbox(
        context: context,
        checked: someChecked ? null : allChecked,
        onRowTap: null,
        onCheckboxChanged: (bool? checked) =>
            _handleSelectAll(checked, someChecked),
        overlayColor: null,
        tristate: true,
      );
    } else {
      tableRows[headerIndex].children![0] = SizedBox();
    }
    displayColumnIndex += 1;
  }

  for (int dataColumnIndex = 0;
      dataColumnIndex < columns.length;
      dataColumnIndex += 1) {
    final DataColumn column = columns[dataColumnIndex];

    final double paddingStart;
    if (dataColumnIndex == 0 &&
        displayCheckboxColumn &&
        checkboxHorizontalMargin != null) {
      paddingStart = effectiveHorizontalMargin;
    } else 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,
    );

    if (effectiveTableColumns[displayColumnIndex] is _NullTableColumnWidth) {
      if (displayColumnIndex == columns.length - 1) {
        effectiveTableColumns[displayColumnIndex] =
            (const IntrinsicColumnWidth(flex: 1.0));
      } else {
        effectiveTableColumns[displayColumnIndex] =
            (const IntrinsicColumnWidth());
      }
    }
    currentQtdCustomLines = 0;
    rowIndex = 0;

    int qtdPreHeaderCustomLines = 0;
    if (customRows != null) {
      for (CustomRow customRow
          in customRows!.where((element) => element.index <= 0)) {
        tableRows[rowIndex].children![displayColumnIndex] =
            customRow.cells[displayColumnIndex];
        if (customRow.index < 0 ||
            customRow.typeCustomRow == TypeCustomRow.ADD) {
          qtdPreHeaderCustomLines++;
        }
        //currentQtdCustomLines++;

        rowIndex++;
      }
    }
    if (useDefaultHeader) {
      tableRows[rowIndex].children![displayColumnIndex] = _buildHeadingCell(
        context: context,
        padding: padding,
        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,
      );
      rowIndex++;
    }

    for (;
        rowIndex <
            (rows.length + 1) +
                (customRows
                        ?.where((element) =>
                            element.typeCustomRow == TypeCustomRow.ADD)
                        .length ??
                    0);
        rowIndex++) {
      int indexCustomRow =
          customRows?.indexWhere((element) => element.index == rowIndex) ??
              -1;
      if (indexCustomRow > -1) {
        tableRows[rowIndex + currentQtdCustomLines]
                .children![displayColumnIndex] =
            customRows![indexCustomRow].cells[dataColumnIndex];
        if (customRows![indexCustomRow].typeCustomRow ==
            TypeCustomRow.REPLACE) {
          continue;
        } else {
          currentQtdCustomLines++;
        }
      }

      /// Checks if the index exists in the list of lines.
      /// It may not exist as the for cycles through the sum of the lines with the custom ones.
      if (rows.length > ((rowIndex - 1) - qtdPreHeaderCustomLines)) {
        final row = rows[(rowIndex - 1) - qtdPreHeaderCustomLines];

        final DataCell cell = row.cells[dataColumnIndex];

        tableRows[rowIndex + currentQtdCustomLines]
            .children![displayColumnIndex] = _buildDataCell(
          onRowTap: row is DataRowPlus ? row.onTap : null,
          onRowSecondaryTap: row is DataRowPlus ? row.onSecondaryTap : null,
          onRowSecondaryTapDown:
              row is DataRowPlus ? row.onSecondaryTapDown : null,
          onSelectChanged: () => row.onSelectChanged != null
              ? row.onSelectChanged!(!row.selected)
              : null,
          context: context,
          padding: padding,
          label: cell.child,
          numeric: column.numeric,
          placeholder: cell.placeholder,
          showEditIcon: cell.showEditIcon,
          onTap: cell.onTap,
          overlayColor: row.color ?? effectiveDataRowColor,
        );
      }
    }
    displayColumnIndex += 1;
  }

  return Container(
    decoration: decoration ?? theme.dataTableTheme.decoration,
    child: Material(
      type: MaterialType.transparency,
      child: Table(
        columnWidths: effectiveTableColumns.asMap(),
        children: tableRows,
      ),
    ),
  );
}