How to convert Enum to number or integer to Enum in dart?| Flutter By Example
In these tutorials, you will learn how to convert an enum to int or int to an enum in dart and flutter programming.
Enum is a custom class type to store the constant values. the values can be strings or numbers. Int is a predefined type in Dart or flutter that holds numeric values.
Automatic conversion is not possible due to different types of data.
Let’s declare Enum constants in Dart or Flutter
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
main() {
print(Day.MONDAY.toString()); //Day.MONDAY
print(Day.MONDAY.index); // zero
}
As you see Enum in dart supports simple constants and does not map with any custom numbers, but the default index is assigned starting from 0.
You can also do the same in Flutter programming.
How to Convert Enum to int in Dart?
As Enum is assigned with index in the order of declaration.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
main() {
var number = Day.THURSDAY.index;
print(number); // 3
print(number.runtimeType); // int
print(Day.MONDAY.runtimeType); // Day
}
Enum index
returns an integer value of an order index of Enum values. Day.THURSDAY.index
returns the value of int i.e 3.
How to Convert int to Enum in Dart?
Sometimes, We have an integer numeric value, that needs to convert to an Enum type.
In this, Enum.values return the List<EnumType>
. So, you have to pass the number to the list using list[number] syntax to get Enum type.
Here is an example for parse Int to Enum in dart and flutter programming
.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
main() {
var number = Day.THURSDAY.index;
var day = Day.values[number];
print(Day.MONDAY.toString());
print(number); // 3
print(number.runtimeType); // int
print(Day.values); // [Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY, Day.SATURDAY, Day.SUNDAY]
print(day); // Day.THURSDAY
print(day.runtimeType); // Day
}
Conclusion
Unlike other programming languages, Dart only supports plain constants without Numeric values assigned to it, Internally it has index property and returned the order of enum values.
learned how to convert Enum to Int or vice versa using index and list with index approaches in Dart or Flutter programming