简体   繁体   中英

Sort a dart list based on constructor parameter

I have defined a class like this,

class Person {
  final int id,
  final String name,
  final String email,
  final int age,

  Person({
    this.id,
    this.name,
    this.email,
    this.age});
}

I have a list of Person like,

List<Person> persons;

Now, I need to sort this list as per its constructor parameters like id or age. How can I do that?

You should do that with sort method.

Here's a simple example, sorting the list by the Person name:

class Person {
  final int id;
  final String name;
  final String email;
  final int age;

  Person({
    this.id,
    this.name,
    this.email,
    this.age});

  @override
  String toString() {
    return "Person $name";
  }
}

void main () {
  List<Person> people = new List();
  people
    ..add(Person(name: "B"))
    ..add(Person(name: "A"))
    ..add(Person(name: "D"))
    ..add(Person(name: "C"));

  people.sort((p1, p2) => p1.name.compareTo(p2.name));
  print(people);
}

Output:

[Person A, Person B, Person C, Person D]

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