71

Is there a simple way to convert an integer value to enum? I want to retrieve an integer value from shared preference and convert it to an enum type.

My enum is:

enum ThemeColor { red, gree, blue, orange, pink, white, black };

I want to easily convert an integer to an enum:

final prefs = await SharedPreferences.getInstance();
ThemeColor c = ThemeColor.convert(prefs.getInt('theme_color')); // something like that
henrykodev
  • 2,674
  • 2
  • 25
  • 36

4 Answers4

109
int idx = 2;
print(ThemeColor.values[idx]);

should give you

ThemeColor.blue
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
24

You can use:

ThemeColor.red.index

should give you

0
Zig Razor
  • 3,022
  • 2
  • 10
  • 29
Farman Ameer
  • 935
  • 1
  • 12
  • 19
0

setup your enum then use the value to get enum by index value

 enum Status { A, B, C, D }

 TextStyle _getColorStyle(Status customStatus) {
      Color retCol;
      switch (customStatus) {
          case Status.A:
             retCol = Colors.green;
             break;
          case Status.B:
             retCol = Colors.white;
             break;
          case Status.C:
             retCol = Colors.yellow;
             break;
          case Status.D:
             retCol = Colors.red;
             break;
        }
       return TextStyle(fontSize: 18, color: retCol);
     }

Call the function

     _getColorStyle(Status.values[myView.customStatus])
Golden Lion
  • 2,792
  • 2
  • 19
  • 29
0

In Dart 2.17, you can use enhanced enums with values (which could have a different value to your index). Make sure you use the correct one for your needs. You can also define your own getter on your enum.

//returns Foo.one
print(Foo.values.firstWhere((x) => x.value == 1));
  
//returns Foo.two
print(Foo.values[1]);
  
//returns Foo.one
print(Foo.getByValue(1));

enum Foo {
  one(1),
  two(2);

  const Foo(this.value);
  final num value;
  
  static Foo getByValue(num i){
    return Foo.values.firstWhere((x) => x.value == i);
  }
}
atreeon
  • 18,328
  • 12
  • 74
  • 95