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]
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']
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']
0 Comments