sortBy method
The sortBy method sorts the list of maps by the given key.
Example:
list.sortBy("price") // create new list with ascending order by according to price
Implementation
List<Map<T, T>> sortBy(String key, {bool isDesc = false}) {
final List<Map<T, T>> maps = whereType<Map<T, T>>()
.where((Map<T, T> element) => element.containsKey(key))
.toList();
try {
maps.sort((Map<T, T> a, Map<T, T> b) {
final T? aValue = a[key];
final T? bValue = b[key];
if (aValue is int && bValue is int) {
return aValue.compareTo(bValue);
}
throw ArgumentError('Values for key "$key" must be of type int');
});
} on ArgumentError {
// If an error is thrown, return an empty list
return <Map<T, T>>[];
}
return isDesc ? maps.reversed.toList() : maps;
}