[英]How do you sort a list by bool in Dart
How do you sort a List
in dart based on a bool
value, the compareTo
method doesn't work with bool
.如何根据bool
值对 dart 中的List
进行排序, compareTo
方法不适用于bool
。 I want true
values to appear at the top of the list.我希望true
值出现在列表的顶部。
You can define your own compare function for bool
and pass it to the sort
method of List
.您可以为bool
定义自己的比较 function 并将其传递给List
的sort
方法。
Example with booleans
as your bool
List
:以booleans
作为bool
List
的示例:
booleans.sort((a, b) {
if(b) {
return 1;
}
return -1;
});
This example tells the sort
method that true
elements should be sorted higher than false
elements.这个例子告诉sort
方法, true
的元素应该比false
的元素排序更高。
booleans.sort((a, b) => b ? 1 : -1);
I just got the same issue, I solve it using the.toString() function.我刚遇到同样的问题,我使用.toString() function 解决了它。 So it's sort separating the 0's to the 1's.因此,它将 0 和 1 分开。
In this case I got a list of forms, some are synced and others no.在这种情况下,我得到了 forms 的列表,有些是同步的,有些没有。
Here's my code:这是我的代码:
final forms = state.forms
..sort(
(a, b) => a.synced.toString().compareTo(b.synced.toString()),
);
Hope it works for you.希望对你有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.