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
37676 次浏览
int idx = 2;
print(ThemeColor.values[idx]);

should give you

ThemeColor.blue

You can use:

ThemeColor.red.index

should give you

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

Warning, make sure you handle non-existent integer with a try/catch.

/// Shows what to do when creating an enum value from a integer value


enum ThemeColor { red, green,}




void main() {
  

try {
final nonExistent = ThemeColor.values[3];
print("Non existent enum is $nonExistent");


}
catch(e) {
print("Non existent enum thrown");
}
}


// Non existent enum thrown

The dartpad: https://dartpad.dev/?id=4e99d3f578311288842a0ab5e069797e