如何在 Dart 3 中正确使用 Comparable?

Dar*_*ath 6 dart flutter

在 Dart SDK 2.xx 中,可以使用任何类作为 mixin。但对于 Dart 3,这不再被允许,如文档中所述: https: //dart.dev/resources/dart-3-migration#mixin

现在我正在为迁移而苦苦挣扎。例如,我将Comparable接口用作 mixin,如下所示:

mixin Compare<T> on Comparable<T> {
  bool operator <=(T other) => compareTo(other) <= 0;
  bool operator >=(T other) => compareTo(other) >= 0;
  bool operator <(T other) => compareTo(other) < 0;
  bool operator >(T other) => compareTo(other) > 0;
}


class Foo with Comparable<Foo>, Compare<Foo> {
  final int value;

  const Foo({required this.value});
  
  @override
  int compareTo(Foo other) => value.compareTo(other.value);
}
Run Code Online (Sandbox Code Playgroud)

但这给了我错误error: The class 'Comparable' can't be used as a mixin because it's neither a mixin class nor a mixin.

但是如果我尝试将它用作这样的界面

mixin Compare<T> on Comparable<T> {
  bool operator <=(T other) => compareTo(other) <= 0;
  bool operator >=(T other) => compareTo(other) >= 0;
  bool operator <(T other) => compareTo(other) < 0;
  bool operator >(T other) => compareTo(other) > 0;
}


class Foo extends Comparable<Foo> with Compare<Foo> {
  final int value;

  const Foo({required this.value});

  @override
  int compareTo(Foo other) => value.compareTo(other.value);
}

Run Code Online (Sandbox Code Playgroud)

我收到另一个错误The class 'Comparable' can't be extended outside of its library because it's an interface class.

那么将我的代码迁移到 Dart 3 的最佳方法是什么?

Dar*_*ath 4

@jamesdlin 的评论回答了我的问题:

mixin Compare<T> implements Comparable<T> {
  bool operator <=(T other) => compareTo(other) <= 0;
  bool operator >=(T other) => compareTo(other) >= 0;
  bool operator <(T other) => compareTo(other) < 0;
  bool operator >(T other) => compareTo(other) > 0;
}


class Foo with Compare<Foo> {
  final int value;

  const Foo({required this.value});
  
  @override
  int compareTo(Foo other) => value.compareTo(other.value);
}
Run Code Online (Sandbox Code Playgroud)

这样,Compare就可以成为 mixin。