Sorting
suggest changeSorting rearranges collection elements into a deterministic order (alphabetical, numerical, chronological, or custom business priorities). In Dart, lists are sorted using an efficient hybrid sorting algorithm (Dual-Pivot Quicksort, falling back to insertion sort for short lists, with $O(n \log n)$ time complexity).
In-Place Sorting with List.sort()
The sort() method mutates the target list in place. When called without arguments, it sorts elements in their natural ascending order (provided elements implement Comparable):
void main() {
// Sorting numbers
final numbers = [42, 7, 19, 3, 99, 14];
numbers.sort();
print(numbers); // [3, 7, 14, 19, 42, 99]
// Sorting strings (case-sensitive Unicode code point order)
final fruits = ['banana', 'Apple', 'cherry', 'date'];
fruits.sort();
print(fruits); // [Apple, banana, cherry, date]
}
Custom Comparator Functions
The sort() method accepts an optional comparator callback:
int Function(T a, T b)
The comparator must return:
- A negative integer if
ashould come beforeb. - Zero if
aandbare equivalent in order. - A positive integer if
ashould come afterb.
Ascending and Descending Order
void main() {
final scores = [85, 92, 74, 99, 61];
// Ascending order
scores.sort((a, b) => a.compareTo(b));
print('Ascending: $scores'); // [61, 74, 85, 92, 99]
// Descending order (invert parameters)
scores.sort((a, b) => b.compareTo(a));
print('Descending: $scores'); // [99, 92, 85, 74, 61]
}
Case-Insensitive String Sorting
void main() {
final names = ['bob', 'Alice', 'charlie', 'David'];
names.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(names); // [Alice, bob, charlie, David]
}
Sorting Custom Objects
class Product {
final String title;
final double price;
final int rating;
Product(this.title, this.price, this.rating);
@override
String toString() => '$title (\$$price, rating: $rating)';
}
void main() {
final products = [
Product('Laptop', 999.0, 4),
Product('Mouse', 25.0, 5),
Product('Keyboard', 85.0, 4),
];
// Sort by price ascending
products.sort((a, b) => a.price.compareTo(b.price));
print('By price: $products');
// Sort by rating descending
products.sort((a, b) => b.rating.compareTo(a.rating));
print('By rating: $products');
}
Multi-Property (Compound) Sorting
When sorting by multiple criteria (e.g. primary sort by rating descending, secondary tie-breaker by price ascending):
void main() {
final items = [
Product('Product A', 50.0, 4),
Product('Product B', 30.0, 4),
Product('Product C', 90.0, 5),
];
items.sort((a, b) {
// Primary: Rating descending
final ratingComparison = b.rating.compareTo(a.rating);
if (ratingComparison != 0) return ratingComparison;
// Secondary: Price ascending (tie-breaker)
return a.price.compareTo(b.price);
});
for (final p in items) {
print('${p.title} - Rating: ${p.rating}, Price: \$${p.price}');
}
}
Non-Destructive (Immutable) Sorting
Because List.sort() mutates the source collection, you must clone the list if you want to leave the original collection untouched:
1. Using Cascade Notation with Spread
final original = [5, 2, 8, 1];
// Create new copy and sort copy in-place
final sortedCopy = [...original]..sort();
print(original); // [5, 2, 8, 1] (Unchanged)
print(sortedCopy); // [1, 2, 5, 8]
2. Using package:collection extensions
package:collection provides convenient .sorted() and .sortedBy() methods:
import 'package:collection/collection.dart';
void main() {
final numbers = [5, 2, 9, 1];
final sortedList = numbers.sorted((a, b) => a.compareTo(b));
print(sortedList); // [1, 2, 5, 9]
final products = [
Product('Desk', 200.0, 3),
Product('Chair', 120.0, 5),
];
// Sort immutably by property
final byPrice = products.sortedBy<num>((p) => p.price);
print(byPrice);
}
Sorting Map Entries
Maps in Dart maintain insertion order. To sort a map by key or value, transform its entries into a list, sort them, and reconstruct a new map:
void main() {
final fruitCounts = {
'oranges': 15,
'apples': 42,
'bananas': 8,
'peaches': 27,
};
// Sort entries by value descending
final sortedEntries = fruitCounts.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
final sortedMap = Map.fromEntries(sortedEntries);
print(sortedMap);
// {apples: 42, peaches: 27, oranges: 15, bananas: 8}
}
Best Practices
- Avoid expensive computations inside comparators: The comparator callback runs $O(n \log n)$ times; do not perform disk reads, regex matching, or network calls inside the comparison lambda.
- Clone before sorting if immutability is required: Never call
.sort()on lists passed into functions as arguments unless in-place mutation is explicitly documented. - Use
package:collectionfor declarative pipelines:.sortedBy()and.sortedByCompare()provide clean, chaining-friendly code.