Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 988
henrykodev Avatar asked Jul 05 '18 11:07

henrykodev


People also ask

Does Dart have enums?

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.

How do you define enum in flutter?

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.

How do you convert string to int in darts?

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.


2 Answers

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

should give you

ThemeColor.blue 
like image 168
Günter Zöchbauer Avatar answered Sep 23 '22 17:09

Günter Zöchbauer


You can use:

ThemeColor.red.index 

should give you

0 
like image 42
Farman Ameer Avatar answered Sep 23 '22 17:09

Farman Ameer