To sort a list in descending order in Dart, you can use the List class's sort method with a custom comparator function.
In this example,
numbers
with integer values.sort
method of the list with a custom comparator function to sort the list in descending order based on integer values.void main() {
List<int> numbers = [5, 2, 8, 1, 3];
numbers.sort((a, b) => b.compareTo(a));
print(numbers);
}
[8, 5, 3, 2, 1]
In this example,
words
with string values.sort
method of the list with a custom comparator function to sort the list in descending order based on string values.void main() {
List<String> words = ['banana', 'apple', 'cherry'];
words.sort((a, b) => b.compareTo(a));
print(words);
}
[cherry, banana, apple]
In this tutorial, we learned How to Sort a List in Descending Order in Dart language with well detailed examples.