Dart Sorting and Ordering
Sorting arranges the values of a list in order. A list sorts itself in place, and a comparator can define a custom order.
Sorting in place
The first print shows the list as built. The sort call rearranges that same list, and the second print shows the new order.
void main() {
var scores = [30, 10, 20];
print(scores);
scores.sort();
print(scores);
}Sorting a copy
List.of builds a second list with the same values. Sorting the copy leaves the first list untouched.
void main() {
var scores = [30, 10, 20];
var ordered = List.of(scores);
ordered.sort();
print(ordered);
print(scores);
}Descending order with a comparator
The comparator compares b to a instead of a to b. That single swap flips the sort into descending order.
void main() {
var scores = [10, 30, 20];
scores.sort((a, b) => b.compareTo(a));
print(scores);
}Sorting strings by length
The comparator compares the lengths of two words. Shorter words come first in the sorted list.
void main() {
var words = ['banana', 'fig', 'apple'];
words.sort((a, b) => a.length.compareTo(b.length));
print(words);
}Reading in reverse
The reversed property gives the values from last to first. The toList call turns that view into a list.
void main() {
var numbers = [1, 2, 3];
print(numbers.reversed.toList());
}Example
void main() {
var temps = [18, 25, 12, 20];
var coldestFirst = List.of(temps);
coldestFirst.sort();
var warmestFirst = List.of(temps);
warmestFirst.sort((a, b) => b.compareTo(a));
print(coldestFirst);
print(warmestFirst);
print(temps);
}Key points
- The sort method rearranges the list itself instead of building a new one.
- Numbers sort from smallest to largest and strings sort alphabetically by default.
- Sorting a copy leaves the original list in its starting order.
- A comparator is a function that compares two values and returns a number.
- Swapping the two sides of a comparison reverses the order.
- The reversed property reads a list from last to first.
In this example, two copies of the temperature list are sorted in opposite orders. The first copy uses the default ascending sort. The second copy uses a comparator that reverses the comparison. The original list keeps its starting order.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does sort do to the list it is called on?