In this article, we will be talking about how to sort a list in descending order in Dart [Also applicable for flutter]. Dart provides the List.sort[] method to sort the list but this method sort the list in ascending order. In this tutorial, we will discuss two approaches to sort the list in descending order.
- Using List.sort[ ] and compareTo
- By sorting the list in ascending order and then reverse the list
Contents
- 1 Approach 1:
- 1.0.1 Example 1:
- 1.0.2 Example 2:
- 2 Approach 2
- 2.0.1 Example:
Approach 1:
In this approach, we use the List.sort[ ] method this method takes a comparator function as an optional parameter. The passed parameter is used to compare the two list items of the list and then sort the list.
Example 1:
List myList = [6, 5, 7, 9, 8, 1, 1, 9]; myList = myList..sort[[a, b] => b - a]; print[myList]; // [9, 9, 8, 7, 6, 5, 1, 1]Example 2:
List myList = [6, 5, 7, 9, 8, 1, 1, 9]; myList = myList..sort[[a, b] => b.compareTo[a]]; print[myList]; // [9, 9, 8, 7, 6, 5, 1, 1]Approach 2
In this approach, we will first sort the list in ascending order using List.sort[ ] and then reverse the sorted list using the reversed property. The reversed property returns an iterable, so we typecast the iterable into List using the List.from[ ] constructor.