[Solved] Sort a list of objects in a specific order

Question

Asked by Yoann F on December 03, 2021 (source).

Let's say I have a list of Place objects :

class Place {
  String name;
  PlaceType type;

  Place({
    required this.name,
    required this.type,
  });
}

enum PlaceType { museum, cinema, supermarket }

What's the best way to sort the list by PlaceType in a specific order (let's say supermarket > cinema > museum) ?

For now I just sort it like below, but I don't know if I can ask for a specific order there.

placesList.sort(
    (Place a, Place b) => a.placeType.name.compareTo(b.placeType.name),
  );

Answer

Question answered by Owl (source).

You can do

PlaceType.values.indexOf("type")

to find the index of the enum value, then compare the index

 placesList.sort(
    (Place a, Place b) => PlaceType.values.indexOf(b.type).compareTo(PlaceType.values.indexOf(a.type)),
  );

Full code example:

class Place {
  String name;
  PlaceType type;

  Place({
    required this.name,
    required this.type,
  });
}

enum PlaceType { museum, cinema, supermarket }

void main() {
  var placesList = [
    Place(name: 'a', type: PlaceType.cinema),
    Place(name: 'b', type: PlaceType.cinema),
    Place(name: 'c', type: PlaceType.museum),
    Place(name: 'd', type: PlaceType.supermarket),
    Place(name: 'e', type: PlaceType.cinema),
    Place(name: 'f', type: PlaceType.supermarket),
    Place(name: 'g', type: PlaceType.museum),
  ];
  
  var v = PlaceType.values;
  placesList.sort(
    (Place a, Place b) => v.indexOf(b.type).compareTo(v.indexOf(a.type)),
  );

  for (var p in placesList) {
     print('${p.name} - ${p.type}');
  }
}

Output:

d - PlaceType.supermarket
f - PlaceType.supermarket
a - PlaceType.cinema
b - PlaceType.cinema
e - PlaceType.cinema
c - PlaceType.museum
g - PlaceType.museum

If you want to make a custom order from PlaceList enum without changing the enum declaration order, you can create a separate variable like this

List<PlaceType> placeTypeOrder = [PlaceType.cinema, PlaceType.museum, PlaceType.supermarket];

then use placeTypeOrder to find the index

placeTypeValues.indexOf(b.type)
DART FLUTTER
SHARE: