Flutter / Dart Convert Int to Enum

EnumsDartFlutter

Enums Problem Overview


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

Enums Solutions


Solution 1 - Enums

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

should give you

ThemeColor.blue

Solution 2 - Enums

You can use:

ThemeColor.red.index

should give you

0

Solution 3 - Enums

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 - Enums

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhenrykodevView Question on Stackoverflow
Solution 1 - EnumsGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - EnumsFarman AmeerView Answer on Stackoverflow
Solution 3 - EnumsGolden LionView Answer on Stackoverflow
Solution 4 - EnumsatreeonView Answer on Stackoverflow