Dart List sort()
Syntax & Examples


Syntax of List.sort()

The syntax of List.sort() method is:

 void sort([int compare(E a, E b)?]) 

This sort() method of List sorts this list according to the order specified by the compare function.

Parameters

ParameterOptional/RequiredDescription
compareoptionala function that compares two elements of the list

Return Type

List.sort() returns value of type void.



✐ Examples

1 Sort a list of numbers

In this example,

  1. We create a list named numbers containing integers.
  2. We then use the sort() method without providing a comparison function, so the list is sorted in ascending order by default.
  3. We print the sorted list to standard output.

Dart Program

void main() {
  List<int> numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
  numbers.sort();
  print(numbers);
}

Output

[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]

2 Sort a list of characters

In this example,

  1. We create a list named characters containing characters.
  2. We then use the sort() method without providing a comparison function, so the list is sorted in ascending order by default.
  3. We print the sorted list to standard output.

Dart Program

void main() {
  List<String> characters = ['d', 'g', 'a', 'c', 'b'];
  characters.sort();
  print(characters);
}

Output

[a, b, c, d, g]

3 Sort a list of words

In this example,

  1. We create a list named words containing strings.
  2. We then use the sort() method without providing a comparison function, so the list is sorted in ascending order by default.
  3. We print the sorted list to standard output.

Dart Program

void main() {
  List<String> words = ['banana', 'apple', 'cherry', 'date'];
  words.sort();
  print(words);
}

Output

[apple, banana, cherry, date]

Summary

In this Dart tutorial, we learned about sort() method of List: the syntax and few working examples with output and detailed explanation for each example.