There doesn't seem to be a way to determine whether an element represents an enum with public APIs.
I ended up importing the library-private EnumElementImpl and type testing against that, which works for now, but maybe there should be an EnumElement interface?
Thanks!
Dart VM version: 2.4.0 (Wed Jun 19 11:53:45 2019 +0200) on "macos_x64"
In the analyzer APIs, the type ClassElement is used to represent classes, mixins and enums. There are getters defined to allow you to identify the latter two cases explicitly (isMixin and isEnum). Are those sufficient for your needs?
They absolutely are. Thanks Brian.
If I have an instance of DartObject that I know is an instance of some enum, AFAIK there is no easy way to figure out which specific value is given.
For example, given the following:
enum Foo { bar, baz }
@MyAnnotation(foo: Foo.bar)
If I have a DartObject containing the @MyAnnotation(...) constant above, I can get the value of foo by calling getField('foo'), no problem. However, while run-time instances of enums have an int index property, this doesn't exist (AFAIK) via the analyzer API's.
I've seen that DartObjects containing an enum have an IntState as their _state, but since this is private, and also only available via DartObjectImpl, there's not really a way that I know of to get the value of some enum constant, other than looping through the fields of the enum type itself.
Is there another way to do this?
Here's a contrived example for anyone who's looking for how to do this:
var joinType = JoinType.left; // Some default value
var joinTypeRdr = // Some DartObject you know to be an instance of JoinType
if (joinTypeRdr != null) {
// Find all the enum constants in JoinType
var joinTypeType = (joinTypeRdr.type as InterfaceType);
var enumFields =
joinTypeType.element.fields.where((f) => f.isEnumConstant).toList();
// Find the index of the matching enum constant.
for (int i = 0; i < enumFields.length; i++) {
if (enumFields[i].constantValue == joinTypeRdr) {
joinType = JoinType.values[i];
break;
}
}
}
@thosakwe Thanks a lot, I was searching exactly for this! I don't know if there's any better way, but it did work for now.
I only changed .constantvalue to .computeConstantValue(), as the former is now deprecated.
Most helpful comment
Here's a contrived example for anyone who's looking for how to do this: