With Dart SDK 2.x.x. it was okay to use any class as mixin. But with Dart 3 this is no longer allowed as stated in the documentation: https://dart.dev/resources/dart-3-migration#mixin
Now I struggle with the migration. For example, I used the Comparable
interface as mixin like this:
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);
}
But this gives me the error error: The class 'Comparable' can't be used as a mixin because it's neither a mixin class nor a mixin.
But if I try to use it as interface like this
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);
}
I get another error The class 'Comparable' can't be extended outside of its library because it's an interface class.
So what is the best way to migrate my code to Dart 3?
2
Answers
The comment of @jamesdlin answers my question:
That why,
Compare
can be a mixin.What you were trying to get can be achieved by extensions.
If you comment extension code, you will get compile time error for
print(a >b);
hence this is valid code as per Dart3