问题
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.
回答1:
enum A { a1, a2, a3}
A.values[index]
回答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.
回答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);
}
}
回答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
来源:https://stackoverflow.com/questions/51452433/dart-how-to-get-an-enum-with-index