How to sort list in Flutter and Dart

Sorting is an important action that we all take on a collection. In any application when you want to display list of data, nobody wants to see the list in some random order. You are always looking to sort list in ascending or descending order. In Flutter application, you will also be sorting your list of data. There are two questions you will be asking to yourself.

  • How to sort list or array in ascending order in Flutter?
  • How to sort list or array in descending order in Flutter?

sort method

Dart has sort method that you can call on a list. Syntax of this method is as below.

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

Default behavior of this method is to sort elements in list in ascending order. Let's take a look at example below.

  var heights = [4, 2, 6, 1, 9, 29];
  print(heights);
  heights.sort();
  print('sort(asc): $heights');

// Output:
 [4, 2, 6, 1, 9, 29]
 sort(asc): [1, 2, 4, 6, 9, 29]

You can see that default behavior of sort is to sort the list in ascending order. Behind the scene, Dart calls compareTo method on pair of elements. If you want to sort the list in descending order, all you have to do is reverse comparison value returned by compareTo method. Following example shows how to accomplish this in Dart.

  var heights = [4, 2, 6, 1, 9, 29];
  print(heights);
  heights.sort();
  print('sort(asc): $heights');
  heights.sort((a,b)=> -a.compareTo(b));
  print('sort(desc): $heights');

// Output:
[4, 2, 6, 1, 9, 29]
sort(asc): [1, 2, 4, 6, 9, 29]
sort(desc): [29, 9, 6, 4, 2, 1]

Above examples used collection of primitive number type. In real application you are going to be sorting lists of class object. Following snippet show how to sort list of objects in Flutter.

priceList.sort((a, b) => -a.recordingTime.compareTo(b.recordingTime));

I have a property named recordingTime in my class. I am looking to sort the list in descending order of time.

This is all you have to do to sorting in Flutter and Dart.

Search

Social

Weather

24.5 °C / 76.1 °F

weather conditions Haze

Monthly Posts

Blog Tags