Enum in Dart
Enum In Dart
An enum or enumeration is used for defining named constant values in a dart programming language. An enumerated type is declared using the keyword enum
. It is used to hold the list of named constant values.
Characteristics Of Enum
- It must contain at least one constant value.
- Enums are declared outside the class.
- Used to store a large number of constant value.
- Makes code more readable and simple.
- It makes the code more reusable and makes it easier for developers.
- Values inside enumeration type cannot be changed dynamically.
Syntax
enum enum_name {
constant_value1,
constant_value2,
constant_value3
}
Example
enum days {
Sunday,
Monday,
Tuesday,
Wednesday,
Thrusday,
Friday,
Saturday }
void main(List<String> args) {
var today = days.Friday;
switch (today) {
case days.Sunday:
print("Today is Sunday.");
break;
case days.Monday:
print("Today is Monday.");
break;
case days.Tuesday:
print("Today is Tuesday.");
break;
case days.Wednesday:
print("Today is Wednesday.");
break;
case days.Thursday:
print("Today is Thursday.");
break;
case days.Friday:
print("Today is Friday.");
break;
case days.Saturday:
print("Today is Saturday.");
break;
}
}
Example For Printing All Values
enum days {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday }
void main(List<String> args) {
for (var day in days.values) {
print(day);
}
}
Enhance Enumerations In Dart
The new version of the dart comes with the support for the enhanced enumerations. The main purpose of this is to increase the readability of the code and to make code a lot more cleaner and efficient to use.
Info
Note: You may need to upgrade your dart SDK as it is only supported in the latest version.
Example
enum Water{
frezing(32),
boiling(212);
final int temperatureInF;
const Water(this.temperatureInF);
}
void main(){
print("The ${Water.frezing.name} point for water is ${Water.frezing.temperatureInF} degree F.");
print("The ${Water.boiling.name} point for water is ${Water.boiling.temperatureInF} degree F. ");
}