Search code snippets, questions, articles...

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]
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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?
0 Comments