How to sort a List in Flutter

October 16, 2022 No comments sort flutter dart list

Introduction

Sometimes, we may wish to sort a List in Flutter/Dart. In this article, we'll look at how to do it.

Check the following posts if you are looking for more information about how to: filter, sort, reverse, update, create a List in Flutter.

And few more about accessing items, removing, updating, and finding them in Flutter Lists.

How to sort a List in Flutter

To sort a list in Flutter/Dart we can use the sort() method.

Using sort() method to sort a list

var list1 = [9, 3, 2, 0, 8];
list1.sort();

var list2 = ['c', 'd','a', 'f', 'b'];
list2.sort();

print(list1);
print(list2);

The output:

[0, 2, 3, 8, 9]
[a, b, c, d, f]

Using a custom compare function to sort a list of objects

class Car {
  String model;
  int yearOfProduction;

  Car(this.model, this.yearOfProduction);

  @override
  String toString() {
    return '{ ${this.model}, ${this.yearOfProduction} }';
  }
}

main() {
  List cars = [];
  cars.add(Car('Seat Ibiza', 2009));
  cars.add(Car('BMW', 2022));
  cars.add(Car('Ferrari', 2019));
  cars.add(Car('Lamborghini', 2010));
  cars.add(Car('Skoda', 2018));

  cars.sort((a, b) => a.yearOfProduction.compareTo(b.yearOfProduction));
  print('Sort by year of production: ' + cars.toString());

  cars.sort((a, b) => a.model.compareTo(b.model));
  print('Sort by model: ' + cars.toString());
}

The output:

Sort by year of production: [{ Seat Ibiza, 2009 }, { Lamborghini, 2010 }, { Skoda, 2018 }, { Ferrari, 2019 }, { BMW, 2022 }]
Sort by model: [{ BMW, 2022 }, { Ferrari, 2019 }, { Lamborghini, 2010 }, { Seat Ibiza, 2009 }, { Skoda, 2018 }]

Extending the Comparable class to sort a list of objects

class Car {
  String model;
  int yearOfProduction;

  Car(this.model, this.yearOfProduction);

  @override
  String toString() {
    return '{ ${this.model}, ${this.yearOfProduction} }';
  }

  // sort by Model first - ascending
  // then year of production -  descending
  @override
  int compareTo(other) {
    int modelComparison = this.model.compareTo(other.model);
    if (modelComparison == 0) {
      return -this.yearOfProduction.compareTo(other.yearOfProduction); // '-' for descending
    }
    return modelComparison;
  }
}

main() {
  List cars = [];
  cars.add(Car('Seat Ibiza', 2009));
  cars.add(Car('BMW', 2022));
  cars.add(Car('Ferrari', 2019));
  cars.add(Car('Ferrari', 2020));

  cars.sort()
  print(cars);
}

The output:

[{ BMW, 2022 }, { Ferrari, 2020 }, { Ferrari, 2019 }, { Seat Ibiza, 2009 }]

Conclusion

In this article, we presented ways to sort a list in Flutter/Dart.

{{ message }}

{{ 'Comments are closed.' | trans }}