I have an Enum
and a function to create it from a String
because i couldn\'t find a built in way to do it
I think my approach is slightly different, but might be more convenient in some cases. Finally, we have parse and tryParse for enum types:
import 'dart:mirrors';
class Enum {
static T parse(String value) {
final T result = (reflectType(T) as ClassMirror).getField(#values)
.reflectee.firstWhere((v)=>v.toString().split('.').last.toLowerCase() == value.toLowerCase()) as T;
return result;
}
static T tryParse(String value, { T defaultValue }) {
T result = defaultValue;
try {
result = parse(value);
} catch(e){
print(e);
}
return result;
}
}
EDIT: this approach is NOT working in the Flutter applications, by default mirrors are blocked in the Flutter because it causes the generated packages to be very large.