dart
Sort a list in ascending and descending order Dart or Flutter
We can use sort() function of Dart to sort a list in ascending and descending order.
List numbers = [10, 30, 50, 40, 20];
// Sort in Ascending order
numbers.sort();
print(numbers);
// -> [10, 20, 30, 40, 50]
// Sort in Descending order
numbers.sort((b, a) => a.compareTo(b));
print(numbers);
// -> [50, 40, 30, 20, 10]
Sort list items in ascending order
Here is an example of sorting all the items of a list in ascending order. We are using sort() function directly to implement it.
Code Example
List alphabets = ['John', 'Albert', 'Carol', 'Hooli'];
alphabets.sort();
print(alphabets);
Output
['Albert', 'Carol', 'Hooli', 'John']
Sort list items in descending order
We will be using sort() and compareTo() functions to sort the list elements in descending order. See the below code example for refernce.
Code Example
List alphabets = ['John', 'Albert', 'Carol', 'Hooli'];
alphabets.sort((b, a) => a.compareTo(b));
print(alphabets);
Output
['John', 'Hooli', 'Carol', 'Albert']
Was this helpful?
Similar Posts
- Remove empty and falsey values from a List in Dart/Flutter
- Check if list is empty in Flutter/Dart
- Reverse a list in Flutter or Dart
- Delete item from a List in Flutter [Dart]
- Loop through a List in Flutter [Dart]
- Remove empty lists from a list of lists and flatten it using Dart
- Check if a String is empty or null in Dart / Flutter