简体   繁体   中英

Dart / Flutter Sort List by Multiple Fields

I was writing my question but had found the solution before posting it. There are many examples about how to sort a list in Dart by comparing two fields. However, I still found it wasn't straight forward, at least for me, to figure out the sorting by more than two fields. I thought it would be worth sharing it under a separate topic.

Here's how I am sorting lists in Dart by three or more fields:

class Student {
  String name;
  String course;
  int age;

  Student(this.name, this.course, this.age);
  
  @override
  String toString() {
    return '{$name, $course, $age}';
  }
}

main() {
  List<Student> students = [];
  students.add(Student('Katherin', 'Dart Potions', 21));
  students.add(Student('Adam Sr', 'Dart Magic', 40));
  students.add(Student('Adam Jr', 'Dart Magic', 15));

  students.sort(
    (a, b) {
      final int sortByCourse = -a.course.compareTo(b.course); // the minus '-' for descending
      if (sortByCourse == 0) {
        final int sortByName = a.name.compareTo(b.name);
        if (sortByName == 0) {
          return a.age.compareTo(b.age);
        }
        return sortByName;
      }
      return sortByCourse;
    },
  );
  
  print('Sort DESC by Course, then ASC by Name and then ASC by Age:\n ${students.toString()}');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM