I know this is an old question and, for now at least, it seems not possible to return E
where E
is a generic enum
, but i'm using this code:
static dynamic asEnumValue(List<dynamic> enumValues, int index) {
try {
return enumValues[index];
} catch (err) {
return null;
}
}
This just allows you not to check every time if index
is a correct value for your Enum type.
If you pass the correct values you can still use enum properties like its index after.
Of course you will get a TypeError
if you don't pass the correct enum values.
Example of use (DartPad):
enum Test {
a,
b,
c
}
dynamic asEnumValue(List<dynamic> enumValues, int index) {
try {
return enumValues[index];
} catch (err) {
return null;
}
}
Test aTest;
Test nullTest1;
Test nullTest2;
void main() {
aTest = asEnumValue(Test.values, 0);
nullTest1 = asEnumValue(Test.values, -1);
nullTest2 = asEnumValue(Test.values, null);
print(aTest);
print(nullTest1);
print(nullTest2);
print(aTest?.index);
print(nullTest1?.index);
print(nullTest2?.index);
}
Output:
Test.a
null
null
0
null
null