dart How to get an enum with index? dart How to get an enum with index? dart dart

dart How to get an enum with index?


enum A { a0, a1, a2 }A.values[index]


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.


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);  }}