Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get an enum value by String #104

Closed
komape opened this issue Jul 29, 2020 · 1 comment
Closed

Get an enum value by String #104

komape opened this issue Jul 29, 2020 · 1 comment

Comments

@komape
Copy link
Contributor

komape commented Jul 29, 2020

Get an enum value by String

Would be nice, if the an enum would have by default a method like getValue(String key) that returns the corresponding enum value to that key.

Current situation

Currently it's necessary to iterate through the values and match them manually.

enum MyEnum {
  a, b, c, d
}
String key = 'c';
for(final MyEnum myEnum in MyEnum.values) {
  if(myEnum.toString() == key) return myEnum);
}
// optional fallback value
return MyEnum.a;

Better solution

enum MyEnum {
  a, b, c, d
}
String key = 'c';
MyEnum myEnum = MyEnum.getValue(key, fallback: MyEnum.a);
@passsy
Copy link
Collaborator

passsy commented Jul 29, 2020

Currently not possible. Dart doesn't allow to define static extensions or factory constructors as extensions dart-lang/language#723

@komape komape closed this as completed Jul 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants