buildComparator<T> function
Builds a Comparator for T that applies sorts in order, using each
column's own GridColumn.comparator where one is defined.
The returned comparator is stable with respect to the input order: rows the sort cannot distinguish keep their relative positions, because sortRows sorts an index-decorated copy.
Implementation
Comparator<T> buildComparator<T>(
List<SortSpec> sorts,
Map<String, GridColumn<T>> columns,
) {
return (T a, T b) {
for (final sort in sorts) {
final column = columns[sort.field];
if (column == null) continue;
final va = column.sortValue(a);
final vb = column.sortValue(b);
if (va == null || vb == null) {
if (va == null && vb == null) continue;
final nullFirst = sort.nulls == NullsPosition.first;
// Null placement is absolute: it does not flip with the direction.
return (va == null) == nullFirst ? -1 : 1;
}
final cmp = column.comparator?.call(va, vb) ??
defaultCompareFor(column.type)(va, vb);
if (cmp != 0) return sort.isAscending ? cmp : -cmp;
}
return 0;
};
}