Search code examples
flutterdartenums

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

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