'Flutter / Dart Convert Int to Enum

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


Solution 1:[1]

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

should give you

ThemeColor.blue

Solution 2:[2]

You can use:

ThemeColor.red.index

should give you

0

Solution 3:[3]

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])

Solution 4:[4]

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

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 Günter Zöchbauer
Solution 2 Zig Razor
Solution 3 Golden Lion
Solution 4 atreeon