Dart programming language logo

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

Written 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

You can use the sort method of List on a list of objects, along with a custom comparator function, to sort the list by the alphabetical order of one of its properties.

Here’s an example of how you can sort a 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"),
// ];

In this example, the sort method takes a comparator function as its argument. The comparator function compares two Person objects and returns a negative, zero, or positive value, depending on whether the first object should be sorted before, in the same position as, or after the second object. In this case, it compares the name property of each object using the compareTo method and sorts them alphabetically.

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 need to have the reversed order when using the sort methods mentioned above. To achieve this, you can use the reversed method followed by toList() to convert the result back to a list. Here’s an example:

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 *