Dart programming language logo

Flutter: how to sort a list of objects by one of its properties

By

in

In Flutter (Dart), there are different posibilities to sort a list of objects by one of its properties. Let’s asume you have a list of Person objects that have a property name on which you want to sort the array.

Dart
List<Person> people = [
  Person(name: "Bob"),
  Person(name: "Charlie"),
  Person(name: "Alice"),
];

Sort a list using the sort() method

Darts List class already provides an abstract sort method, to sort a list according to the order specified by the compare function. By using a custom comparator function as parameter, the values of this list can be sorted by alphabetical order of one of its properties.

Here’s an example to sort the list of objects by their name property:

Dart
people.sort((a, b) => a.name.compareTo(b.name));

// The sorted result:
// [
//   Person(name: "Alice"),
//   Person(name: "Bob"),
//   Person(name: "Charlie"),
// ];

The comparator function in the example above compares two Person objects. It returns a negative, zero, or positive value, depending on the value of each name property. This indicates whether the first object should be sorted before, in the same position as, or after the second object.

Sort a list using the sortBy() method

Another way to sort by one property is to use the sortBy method from the dart:collection package. This method […] sorts elements by the natural order of their keyOf property […]:

Dart
import 'dart:collection';

people.sortBy((person) => person.name);

// The sorted result:
// [
//   Person(name: "Alice"),
//   Person(name: "Bob"),
//   Person(name: "Charlie"),
// ];

This will sort the list of people based on the name property.

Reverse the order of a sorted list

However, you might require the reversed order when using the sort methods discussed above. To achieve this, you can simply use the reversed method followed by toList() afterwards, to convert the result back to a list:

Dart
// Reversing the list
List<int> reversedPeople = people.reversed.toList();

// The reversed result:
// [
//   Person(name: "Charlie"),
//   Person(name: "Bob"),
//   Person(name: "Alice"),
// ];

This code uses the reversed method to reverse the order of the given list and toList() to convert the result back to a list.



Comments

Leave a Reply

Your email address will not be published. Required fields are marked *