Sort list items in ascending order
Sort list items in descending order
How to reverse a list in dart
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']
How to reverse a list in dart
To revese a list in Dart, we have one inbuilt property called reversed. This property returns one iterable of the items in the list in reversed order. We can convert the iterable to a list using toList method.
Below is the definition of reversed :
Iterable<E> get reversed;
Example of reversing a list in Dart:
Let’s check how this property works :
void main() {
var list = new List();
list.add(1);
list.add(2);
list.add(3);
print(list);
var reversed = list.reversed;
print(reversed.toList());
}
If you run this Dart program, it will print the below output:
[1, 2, 3]
[3, 2, 1]
Oldest comments (0)