buildGroups<T> function
Groups rows by groups, computing aggregations at every level.
Rows arrive already sorted and filtered; grouping preserves their relative order inside each bucket.
Implementation
List<GroupNode<T>> buildGroups<T>(
List<T> rows,
List<GroupSpec> groups,
Map<String, GridColumn<T>> columns, {
List<Aggregation> aggregations = const [],
int depth = 0,
String parentPath = '',
List<GroupKey> parentKeys = const [],
}) {
if (groups.isEmpty || rows.isEmpty) return const [];
final spec = groups.first;
final column = columns[spec.field];
final buckets = <Object?, List<T>>{};
final labels = <Object?, String>{};
for (final row in rows) {
final raw = column == null ? null : column.value(row);
final key = spec.keyFor(raw);
buckets.putIfAbsent(key, () => <T>[]).add(row);
labels[key] ??= spec.labelFor(key);
}
// Header order follows the column's own comparator, so that groups sort
// the way the column sorts: a priority column ordering High/Medium/Low by
// comparator used to produce headers in alphabetical order. A keyOf
// bucketing function makes the keys something the column's comparator has
// never seen, so that case keeps the generic order.
final compare = spec.keyOf == null
? (column?.comparator ??
defaultCompareFor(column?.type ?? ColumnType.text))
: compareValues;
final nullsFirst = spec.nulls == NullsPosition.first;
final keys = buckets.keys.toList()
..sort((a, b) {
// Nulls are placed before the direction is applied, so the blank group
// does not jump to the top when the headers are reversed.
if (a == null || b == null) {
if (a == null && b == null) return 0;
return (a == null) == nullsFirst ? -1 : 1;
}
final cmp = compare(a, b);
return spec.direction == SortDirection.ascending ? cmp : -cmp;
});
final rest = groups.sublist(1);
return [
for (final key in keys)
() {
final bucket = buckets[key]!;
final segment = groupPathSegment(spec.field, key);
final path = parentPath.isEmpty ? segment : '$parentPath\u001f$segment';
final keys = [...parentKeys, GroupKey(spec.field, key)];
final children = buildGroups<T>(
bucket,
rest,
columns,
aggregations: aggregations,
depth: depth + 1,
parentPath: path,
parentKeys: keys,
);
return GroupNode<T>(
field: spec.field,
key: key,
label: labels[key]!,
depth: depth,
path: path,
keys: keys,
children: children,
rows: children.isEmpty ? bucket : const [],
aggregates: computeAggregates<T>(
bucket,
aggregations,
(row, field) => columns[field]?.value(row),
),
);
}(),
];
}