flutter PaginatedDataTable row color

351 views Asked by At

I use a PaginatedDataTable and I wish that the row been colored when selected.

I found that on simple DataTable:

    DataRow(
        color: MaterialStateColor.resolveWith(
               (Set<MaterialState> states) => states.contains(MaterialState.selected)
                                                          ? Colors.blue
                                                          : Colors.blue[400]),
       selected: address.isSelected,   

but nothing for PaginatedDataTable ...

Can you help me guys?

1

There are 1 answers

0
Keegan Skeate On

You can either set dataTableTheme in your ThemeData:

dataTableTheme: DataTableThemeData(
  dataRowColor: MaterialStateProperty.resolveWith<Color?>(
      (Set<MaterialState> states) {
    if (states.contains(MaterialState.selected)) {
      return Colors.blue;
    }
    return Colors.transparent;
  }),
),

Or you can create a custom class that extends DataTableSource:

/// Table data.
class TableData<T> extends DataTableSource {
  TableData({
    required this.data,
    required this.cellsBuilder,
    this.onTap,
    this.onSelect,
    this.isSelected,
  });

  // Properties.
  final List<T> data;
  final List<DataCell> Function(T item) cellsBuilder;
  final void Function(T item)? onTap;
  final void Function(bool selected, T item)? onSelect;
  final bool Function(T item)? isSelected;

  @override
  DataRow getRow(int index) {
    final item = data[index];
    return DataRow.byIndex(
      index: index,
      cells: cellsBuilder(item),
      color: MaterialStateColor.resolveWith(_getDataRowColor),
      selected: isSelected == null ? false : isSelected!(item),
      onSelectChanged: isSelected == null
          ? null
          : (bool? selected) => onSelect!(selected ?? false, item),
      onLongPress: () => onTap!(item),
    );
  }

  @override
  int get rowCount => data.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => 0;

  // Define the color of the row.
  Color _getDataRowColor(Set<MaterialState> states) {
    if (states.contains(MaterialState.selected)) {
      return Colors.blue;
    }
    return Colors.transparent;
  }
}

And use the custom class in your PaginatedDataTable:

PaginatedDataTable(
  columns: tableHeader,
  source: TableData<Map<String, dynamic>>(
    data: data,
    cellsBuilder: _buildCells,
  ),
);

You will need to have defined your tableHeader and your _buildCells function. Also, I haven't yet figured out how to change the whole row color on hover, but this is at least a start for you. If anyone knows how to change the whole rows color, then this code can be improved upon.