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#.
Enums are still restricted, you cannot implement the interface other than by creating an enum .
Dart supports the use of generic types (often denoted as T ) in three general places: In a function's arguments. In local variables inside a function. In a function's return type.
Creating an instance of a generic type in DART 94 Enum from String 125 Add methods or values to enum in dart 91 Pass a typed function as a parameter in Dart 112 Dart Multiple Constructors 61 Flutter / Dart Convert Int to Enum 6 Passing enum type as argument in Dart 2 2
Another solution is defining an extension. The extension can be used if Dart version is 2.7 or later. When we want to handle the value as a real enum value this is the only way. If we use static value in class it is no longer enum but string or number.
In C# 7.3, Microsoft added the ability to specify an Enum as a generic constraint, like this: Whenever you have a generic method, it’s a good idea to use generic type constraints.
Before the Enum generic type constraint feature was added, your best option was to use the struct generic type constraint, and optionally do an enum type check using typeof (T).IsEnum, like this: The following code tries to use this method with a struct type (Int32): 400.
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);
It is now possible to constrain a generic type to an Enum since Dart 2.16.
You can do so in a following way:
class MyClass<T extends Enum> {}
Now you can pass to the generic parameter T
of MyClass
only enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With