data是一个数组,包含一个类,比如List我想根据这个列表的长度进行过滤,但是过滤不起作用。你能帮助我吗?我留下了我在下面尝试的代码。data .map((e) => e.likes.length) .toList() .sort((a, b) => b.compareTo(a));
data .map((e) => e.likes.length) .toList() .sort((a, b) => b.compareTo(a));
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]
1条答案
按热度按时间2ul0zpep1#
用下面的代码试试
示例:
输出:
编辑:反之亦然
请使用以下内容:
输出: