17

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.

songfei
  • 171
  • 1
  • 1
  • 3

5 Answers5

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

// e.g: A.values[0] == A.a0
// In Dart, arrays start at 0. A.values is a regular array, so naturally, its index starts at 0.
Null Mastermind
  • 1,038
  • 10
  • 8
0

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.

lrn
  • 64,680
  • 7
  • 105
  • 121
0

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

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
Ansharja
  • 1,237
  • 1
  • 14
  • 37
-1
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;
    }
}
Jerin
  • 688
  • 1
  • 9
  • 21