我正在尝试将音乐列表与发行日期进行比较。但我可以在没有releaseDate 的情况下检索音乐,当我想对它们进行排序时,出现错误。
如何对可为空的日期时间进行排序/比较并将 null releaseDate 放在末尾?
_followedMusic.sort((a, b) {
if (a.releaseDate != null && b.releaseDate != null)
return a.releaseDate.compareTo(b.releaseDate);
else
// return ??
});
Run Code Online (Sandbox Code Playgroud)
谢谢
如果您查看以下文档compareTo
:
当将此值与其他值进行比较时,返回一个类似于 Comparator 的值。也就是说,如果 this 排在 other 之前,则返回负整数;如果 this 排在 other 之后,则返回正整数;如果 this 和 other 排在一起,则返回零。
https://api.dart.dev/stable/2.10.0/dart-core/Comparable/compareTo.html
因此,您compareTo
应该只返回值-1
,0
或者1
根据比较对象是否应该在当前对象之前、相同位置或之后。
因此,在您的情况下,如果您希望null
条目位于排序列表的开头,您可以执行以下操作:
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return -1;
} else if (s2 == null) {
return 1;
} else {
return s1.compareTo(s2);
}
});
print(list); // [null, null, a, b, c]
}
Run Code Online (Sandbox Code Playgroud)
或者如果你想要null
最后的:
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return 1;
} else if (s2 == null) {
return -1;
} else {
return s1.compareTo(s2);
}
});
print(list); // [a, b, c, null, null]
}
Run Code Online (Sandbox Code Playgroud)
或者,正如 @lrn 建议的那样,以更简短、更有效的方式制作最后一个示例(但可能不那么可读:)):
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) => s1 == null
? s2 == null
? 0
: 1
: s2 == null
? -1
: s1.compareTo(s2));
print(list); // [a, b, c, null, null]
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1870 次 |
最近记录: |