dart 按类的长度属性排序,该类在flutter中存储为List

snz8szmq  于 2023-04-03  发布在  Flutter
关注(0)|答案(1)|浏览(128)

data是一个数组,包含一个类,比如List我想根据这个列表的长度进行过滤,但是过滤不起作用。你能帮助我吗?我留下了我在下面尝试的代码。
data .map((e) => e.likes.length) .toList() .sort((a, b) => b.compareTo(a));

2ul0zpep

2ul0zpep1#

用下面的代码试试

var sortedList = data.toList()..sort((a, b) => a.likes.length.compareTo(b.likes.length));

示例:

class Post {
  List<String> likes;
  Post({required this.likes});
}

void main() {
  List<Post> posts = [
    Post(likes: ['user1', 'user2', 'user3']),
    Post(likes: ['user4', 'user5']),
    Post(likes: ['user6', 'user7', 'user8', 'user9']),
    Post(likes: ['user10']),
  ];
  posts.sort((a, b) => a.likes.length.compareTo(b.likes.length));

  posts.forEach((post) => print(post.likes));
}

输出:

[user10]
[user4, user5]
[user1, user2, user3]
[user6, user7, user8, user9]

编辑:反之亦然

请使用以下内容:

posts.sort((a, b) => b.likes.length.compareTo(a.likes.length));

输出:

[user6, user7, user8, user9]
[user1, user2, user3]
[user4, user5]
[user10]

相关问题