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
Enumerated types (also known as enumerations or enums) are primarily used to define named constant values. The enum keyword is used to define an enumeration type in Dart.
An enumeration in Dart is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over. Every value of an enumeration has an index. The first value has an index of 0.
A string can be cast to an integer using the int. parse() method in Dart. The method takes a string as an argument and converts it into an integer.
int idx = 2; print(ThemeColor.values[idx]);
should give you
ThemeColor.blue
You can use:
ThemeColor.red.index
should give you
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With