[英]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. 现在,我需要根据其构造函数参数(例如id或age)对该列表进行排序。 How can I do that?
我怎样才能做到这一点?
You should do that with sort method. 您应该使用sort方法。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.