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 {
  List<DataGridRow> get rows => _employees
      .map<DataGridRow>((dataRow) => DataGridRow(cells: [
            DataGridCell<int>(columnName: 'id', value:,
            DataGridCell<String>(columnName: 'name', value:,
                columnName: 'designation', value: dataRow.designation),
            DataGridCell<int>(columnName: 'salary', value: dataRow.salary),

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

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

     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, b, sortColumn);


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

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