I want to create 2 Enums (or even more later on) with a same field, and a same method relating to it, like:
enum Enum1 {
A1('A1', 1),
B1('B1', 2);
String name;
int x1;
Enum1(this.name, this.x1);
String concat(String s) {
return name + s;
}
}
enum Enum2 {
A2('A2', 3),
B2('B2', 4);
String name;
int x2;
Enum2(this.name, this.x2);
String concat(String s) {
return name + s;
}
}
What should I do to reuse the code of identical methods in different Enums?
Namely, how can I reuse the codes related to name and concat in the previous example?
I have tried to use a class to do implementation for both Enums, but it kept prompting me that I have to re-implement the concat method and the getter of name respectively in each Enum.
My failed attempt is like:
class Reuse {
String name;
String concat(String s) {
return name + s;
}
}
enum Enum1 implements Reuse {
A1('A1',1), B1('B1',2);
int x1;
String name;
Enum1(this.name, this.x1);
String concat(String s);
}
enum Enum2 implements Reuse {
A2('A2',3), B2('B2',4);
int x2;
String name;
Enum2(this.name, this.x2);
String concat(String s);
}
This can be achieved by declaring
Reuseas a mixin, and declaring the enums aswith Reuserather thanimplements Reuse.The
implementskeyword does not inherit the implementation of methods whileextendsandwithdo give you the implementation of the methods. And since enums in dart are restricted from usingextends, this leaveswithas the only option, and you can only usewithwith mixins.