Dart 排序/比较可为空的日期时间

Nao*_*fix 2 datetime dart

我正在尝试将音乐列表与发行日期进行比较。但我可以在没有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)

谢谢

jul*_*101 7

如果您查看以下文档compareTo

当将此值与其他值进行比较时,返回一个类似于 Comparator 的值。也就是说,如果 this 排在 other 之前,则返回负整数;如果 this 排在 other 之后,则返回正整数;如果 this 和 other 排在一起,则返回零。

https://api.dart.dev/stable/2.10.0/dart-core/Comparable/compareTo.html

因此,您compareTo应该只返回值-10或者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)

  • 如果两个值都是“null”,则应该返回零,否则您将面临风险……好吧,可能不是很多,但已知一些特别幼稚的排序实现会使用不一致的比较函数永远循环。那么 `=> s1 == null ?s2==空?0 : 1 : s2 == null ?-1:s1.compareTo(s2)`。 (2认同)