Search code examples
flutterdart

Dart - Constrain a generic type (T) to an Enum


Is there a way to constrain a generic type to be an enum, something like the following?

class MyClass<T extends enum> {}

Something like this in C#.


Solution

  • It is not possible in Dart. I had the same issue converting enum properties to a SQLite database (which can hold only its numeric types), so I needed enum.values to "parse" the integer to enum and enum.index to convert the enum value to an int.

    The only way possible is to cast the enum to dynamic or passing the enum values.

    Example:

    T mapToEnum<T>(List<T> values, int value) {
      if (value == null) {
        return null;
      }
    
      return values[value];
    }
    
    dynamic enumToMap<T>(List<T> values, T value) {
      if (value == null) {
        return null;
      }
    
      return values.firstWhere((v) => v == value);
    }
    

    So I can use like this:

    final SomeEnum value = SomeEnum.someValue;
    final int intValue = enumToMap(SomeEnum.values, value);
    final SomeEnum enumValue = mapToEnum(SomeEnum.values, value.index);