Expose a means to determine whether an element represents an enum type

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”

Author: Fantashit

1 thought on “Expose a means to determine whether an element represents an enum type

  1. 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;
        }
      }
    }
    

Comments are closed.