0

Minimal reproducible code:

abstract class FooEnum extends Enum {
  // Some abstract methods...
}

enum One implements FooEnum { a, b }
enum Two implements FooEnum { x, y }

FooEnum getFooEnum(String string) {
  // Too much boiler plate code, how to do it in a better way?
  if (string == 'One.a') return One.a;
  else if (...) // other cases.
}

Right now I'm doing it manually (error prone). So, how can I get an enum from a String?

iDecode
  • 22,623
  • 19
  • 99
  • 186
  • Does this answer your question? [Enum from String](https://stackoverflow.com/questions/27673781/enum-from-string) – Peter Bagyinszki Nov 10 '22 at 09:46
  • @PeterBagyinszki No, they both are different questions. Please don't just read the title, read the body also and my question's body is not that long to read. – iDecode Nov 10 '22 at 09:58

1 Answers1

0

If you only want to use pure dart without flutter or any packages you could do this:

FooEnum? getFooEnum(String string) {
  final classValue = string.split('.');
  if (classValue.length != 2) {
    return null;
  }
  try {
    switch (classValue[0]) {
      case 'One':
        return One.values.byName(classValue[1]);
      case 'Two':
        return Two.values.byName(classValue[1]);
    }
  } on ArgumentError {
    return null;
  }
  return null;
}

With the collection package you could do this:

FooEnum? getFooEnum(String string) {
  return (One.values.firstWhereOrNull((e) => e.toString() == string) ??
    Two.values.firstWhereOrNull((e) => e.toString() == string)) as FooEnum?;
}

I haven't looked into why the cast is needed, but it was a quick way to fix the problem that occures without it.

iDecode
  • 22,623
  • 19
  • 99
  • 186
Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • Thanks, I thought this way but then I thought there must be a better way to handle it. You can make one change in your code, instead of returning `One.values.firstWhere(...)`, you can use `One.values.byName(classValue[1])` – iDecode Nov 10 '22 at 15:04
  • Yeah I edited it. Do note that the error you have to catch is different. I would strongly consider using the collection package instead though :) – Robert Sandberg Nov 10 '22 at 15:35