compare method

  1. @protected
int compare(
  1. DataGridRow? a,
  2. DataGridRow? b,
  3. SortColumnDetails sortColumn
)

Called when the sorting is applied for column. This method compares the two objects and returns the order either they are equal, or one is greater than or lesser than the other.

You can return the following values,

  • a negative integer if a is smaller than b,
  • zero if a is equal to b, and
  • a positive integer if a is greater than b.

You can override this method and do the custom sorting based on your requirement. Here sortColumn provides the details about the column which is currently sorted with the sort direction. You can get the currently sorted column and do the custom sorting for specific column.

The below example shows how to sort the name column based on the case insensitive in ascending or descending order.

class EmployeeDataSource extends DataGridSource {
  @override
  List<DataGridRow> get rows => _employees
      .map<DataGridRow>((dataRow) => DataGridRow(cells: [
            DataGridCell<int>(columnName: 'id', value: dataRow.id),
            DataGridCell<String>(columnName: 'name', value: dataRow.name),
            DataGridCell<String>(
                columnName: 'designation', value: dataRow.designation),
            DataGridCell<int>(columnName: 'salary', value: dataRow.salary),
          ]))
      .toList();

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((dataCell) {
          return Text(dataCell.value.toString());
        }).toList());
  }

 @override
  int compare(DataGridRow? a, DataGridRow? b, SortColumnDetails sortColumn) {
   if (sortColumn.name == 'name') {
     final String? valueA = a
         ?.getCells()
         .firstWhereOrNull((dataCell) => dataCell.columnName == 'name')
         ?.value;
     final String? valueB = b
         ?.getCells()
         .firstWhereOrNull((dataCell) => dataCell.columnName == 'name')
         ?.value;

     if (valueA == null || valueB == null) {
       return 0;
     }

     if (sortColumn.sortDirection == DataGridSortDirection.ascending) {
       return valueA.toLowerCase().compareTo(valueB.toLowerCase());
     } else {
       return valueB.toLowerCase().compareTo(valueA.toLowerCase());
     }
   }

   return super.compare(a, b, sortColumn);
 }

Implementation

@protected
int compare(DataGridRow? a, DataGridRow? b, SortColumnDetails sortColumn) {
  Object? getCellValue(List<DataGridCell>? cells, String columnName) {
    return cells
        ?.firstWhereOrNull(
            (DataGridCell element) => element.columnName == columnName)
        ?.value;
  }

  final Object? valueA = getCellValue(a?.getCells(), sortColumn.name);
  final Object? valueB = getCellValue(b?.getCells(), sortColumn.name);
  return _compareTo(valueA, valueB, sortColumn.sortDirection);
}