Skip to content

Instantly share code, notes, and snippets.

@IsmailAlamKhan
Created November 30, 2021 09:21
Show Gist options
  • Save IsmailAlamKhan/2ae0c1ff3ef08a2f5a68556cfef7cedc to your computer and use it in GitHub Desktop.
Save IsmailAlamKhan/2ae0c1ff3ef08a2f5a68556cfef7cedc to your computer and use it in GitHub Desktop.
void main() {
hello();
}
enum RequestType1 { image, video }
extension on String {
T getEnum<T extends Enum>(List<T> values) {
return values.firstWhere(
(e) => describeEnum(e) == this,
orElse: () => throw Exception('Invalid enum value'),
);
}
}
extension on Enum {
String getString() => describeEnum(this);
}
String describeEnum(Object enumEntry) {
final String description = enumEntry.toString();
final int indexOfDot = description.indexOf('.');
assert(
indexOfDot != -1 && indexOfDot < description.length - 1,
'The provided object "$enumEntry" is not an enum.',
);
return description.substring(indexOfDot + 1);
}
void hello() {
printEnum('video'.getEnum<RequestType1>(RequestType1.values));
}
void printEnum(RequestType1 requestType1) => print(requestType1.getString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment