The syntax of List.sort() method is:
void sort([int compare(E a, E b)?])
This sort() method of List sorts this list according to the order specified by the compare
function.
Parameter | Optional/Required | Description |
---|---|---|
compare | optional | a function that compares two elements of the list |
List.sort() returns value of type void
.
In this example,
numbers
containing integers.sort()
method without providing a comparison function, so the list is sorted in ascending order by default.void main() {
List<int> numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
numbers.sort();
print(numbers);
}
[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
In this example,
characters
containing characters.sort()
method without providing a comparison function, so the list is sorted in ascending order by default.void main() {
List<String> characters = ['d', 'g', 'a', 'c', 'b'];
characters.sort();
print(characters);
}
[a, b, c, d, g]
In this example,
words
containing strings.sort()
method without providing a comparison function, so the list is sorted in ascending order by default.void main() {
List<String> words = ['banana', 'apple', 'cherry', 'date'];
words.sort();
print(words);
}
[apple, banana, cherry, date]
In this Dart tutorial, we learned about sort() method of List: the syntax and few working examples with output and detailed explanation for each example.