Reputation: 11592
Is it possible to use the enum constructor directly?
void main() {
print(Test(1));
}
enum Test {
test1(1),
test2(2);
final int id;
const Test(this.id);
}
This will give the following error:
generative enum constructors can only be used as targets of redirection
I know that it can be solved like this:
enum Test {
test1(1),
test2(2);
final int id;
const Test(this.id);
factory Test.fromId(int id) {
return values.firstWhere((e) => e.id == id);
}
}
But it feels like there must be a way to avoid this boiler plate factory?
Upvotes: 16
Views: 7522
Reputation: 11
While it seems to be necessary to use factory, you can have your factory to be unnamed and use a named constructor inside the class, and therefore "looks easier" when using the enum factory.
enum Test {
error._inner(0),
test1._inner(1),
test2._inner(2);
final int id;
const Test._inner(this.id);
factory Test(int id) {
return values.firstWhere((e) => e.id == id, orElse:()=>error);
}
}
Upvotes: 1
Reputation: 23357
I don't think there is an easier way than that factory. My personal opinion is also that it really isn't that much of boiler plate, but that's subjective.
One reason I can think of why there isn't an easier method, is because the id
in your case is not unique, this is perfectly valid:
enum Test {
test1(1),
secondtest1(1),
test2(2);
final int id;
const Test(this.id);
factory Test.fromId(int id) {
return values.firstWhere((e) => e.id == id);
}
}
Now you will never be able to get the secondtest1
using the fromId
Upvotes: 28