To sort a List in Dart, you can use the sort()
method. For sorting in ascending order, you simply call the sort()
method on the list object. For sorting in descending order, you can use the sort()
method with a comparison function.
In this example,
List
named numbers
and initialize it with integer values.sort()
method on the numbers
list to sort it in ascending order.sort()
method sorts the elements in natural order.void main() {
List<int> numbers = [5, 2, 8, 1, 3];
numbers.sort();
print('Sorted list in ascending order: \$numbers');
}
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
List
named numbers
and initialize it with integer values.sort()
method on the numbers
list with a comparison function to sort it in descending order.sort()
method with the comparison function sorts the elements in reverse natural order.void main() {
List<int> numbers = [5, 2, 8, 1, 3];
numbers.sort((a, b) => b.compareTo(a));
print('Sorted list in descending order: \$numbers');
}
Sorted list in descending order: [8, 5, 3, 2, 1]
In this tutorial, we learned How to Sort a List in Dart language with well detailed examples.