Debug School

rakesh kumar
rakesh kumar

Posted on

How to sort by alphabetical flutter app?

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);
Enter fullscreen mode Exit fullscreen mode
Output

['Albert', 'Carol', 'Hooli', 'John']
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
Output

['John', 'Hooli', 'Carol', 'Albert']
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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());
}
Enter fullscreen mode Exit fullscreen mode

If you run this Dart program, it will print the below output:

[1, 2, 3]
[3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Image description
Image description

click here
click here
click here
click here

Top comments (0)