Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use enum constructor directly in Dart

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading