'dart How to get an enum with index?
I defined an enum:
enum TestEnum {
test1,
test2,
}
and I want make an enum with index:
E buildEnum<E extends ?????????????????>(int index) {
try {
return E.values[index];
}
catch(e) {
return null;
}
}
I don't know the type of enum.
Solution 1:[1]
enum A { a0, a1, a2 }
A.values[index]
// e.g: A.values[0] == A.a0
Solution 2:[2]
You cannot make static accesses on a type parameter, so this cannot work.
There is no way except reflection (dart:mirrors) to go from a value to a static member of its type.
Solution 3:[3]
I know what you mean, but it doesn't seem to be supported. At least you can override it:
enum YourEnum { a1, a2, a3 }
enum AnotherEnum { b1, b2, b3 }
abstract class ToolsEnum<T> {
T getEnumFromString(String value);
}
class YourClass with ToolsEnum<YourEnum> {
@override
YourEnum getEnumFromString(String value) {
return YourEnum.values
.firstWhere((e) => e.toString() == "YourEnum." + value);
}
}
class AnotherClass with ToolsEnum<AnotherEnum> {
@override
AnotherEnum getEnumFromString(String value) {
return AnotherEnum.values
.firstWhere((e) => e.toString() == "AnotherEnum." + value);
}
}
Solution 4:[4]
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
Solution 5:[5]
enum My {a, b, c}
and add an extension class
extension MyExt on My {
@overrride
int get index {
if(this == SS.a)
return 1;
else if(this == SS.b)
return 2
else return 3;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | lrn |
| Solution 3 | Leandro Carvalho |
| Solution 4 | Ansharja |
| Solution 5 | Jerin |
