Flutter 如何使用省道排序方法(带示例代码)
存储库在下面 我按startedDate对项目进行排序,然后尝试在startedDate范围内按startedDatetime进行排序Flutter 如何使用省道排序方法(带示例代码),flutter,sorting,dart,Flutter,Sorting,Dart,存储库在下面 我按startedDate对项目进行排序,然后尝试在startedDate范围内按startedDatetime进行排序 class Item { //required int id; DateTime createdAt; DateTime startedDate; DateTime endedDate; //optional DateTime startedDatetime; DateTime endedDatetime; 在编写if表达式时
class Item {
//required
int id;
DateTime createdAt;
DateTime startedDate;
DateTime endedDate;
//optional
DateTime startedDatetime;
DateTime endedDatetime;
在编写if表达式时,我注意到返回0的顺序不正确
第一个排序结果
result
id, startedDate, startedDateTime, endedDatetime
2, 2020-11-06 00:00:00.000, null , null
1, 2020-11-06 00:00:00.000, 2020-11-06 08:00:00.000, 2020-11-06 17:00:00.000
3, 2020-11-06 00:00:00.000, null , null
4, 2020-11-07 00:00:00.000, 2020-11-07 08:00:00.000, 2020-11-07 17:00:00.000
5, 2020-11-07 00:00:00.000, null , null
6, 2020-11-07 00:00:00.000, null , null
7, 2020-11-08 00:00:00.000, 2020-11-08 08:00:00.000, 2020-11-08 17:00:00.000
result
id, startedDate, startedDateTime, endedDatetime
12, 2020-11-12 00:00:00.000, null , null
1, 2020-11-06 00:00:00.000, 2020-11-06 08:00:00.000, 2020-11-06 17:00:00.000
3, 2020-11-06 00:00:00.000, null , null
.
.
在这里,startedDate已正确排序,但仍然不是理想的结果
我的理解。
我认为如果大于或等于1,sort方法将交换item1和item2,如果小于0,则什么也不做
但结果如下(第二个排序结果)
为什么?
还有,我该如何解决这个问题
测试如下
看起来您需要两级比较:首先比较startedDate,如果非零,则返回差值,否则(即如果startedDate-s相等)比较startedDateTime。整个排序将在一次调用中完成
顺便说一句,请查看
sort()
文档,可能它不能保证“相等”项保持其相对顺序…我通过一次排序处理所有项,得到了理想的结果,如下所示
我已经审阅了以下文档>>并且整个排序将在一次呼叫中完成。您审阅了吗?所以您应该已经看到了这一部分:比较器可以将对象作为相等对象进行比较(返回零),即使它们是不同的对象。排序函数不能保证是稳定的,因此在结果中可能以任何顺序出现比较为相等的不同对象。这正是您得到的结果:startedDateTime相等的对象按该值分组在一起,但它们以前由startedDate确定的顺序不会保留。同样适用于使用comaparator
返回0的排序代码>–上面写着所有商品都是一样的,但它们不遵守先前的订单。谢谢。我终于明白了文档的含义!