Dart Enumeratio
A collection of values known as elements, members, etc. makes up an enumeration. This was crucial when we used the small range of values for the variable to complete the task. For instance, consider that each of the seven days of the month—Sun, Mon, Tue, Wed, Thur, Fri, and Sat—can only represent one of the days of the month.
Initializing an Enumeration
The list of valid identifiers separated by commas is appended to the declaration of the enumeration, which is made using the enum keyword. Within the curly braces {}, is this list. Below is the syntax.
Syntax
enum {
const1,
const2,
....., constN
}
The list of identifiers included in the curly bracket and the name of the enum type are indicated here by the enum_name.
Every identifier in the list of enumerations has a certain index point. The first enumeration’s index is 0, the second enumeration’s index is 1, and so forth.
Example
Let’s define a list of the months in a year.
enum EnumofYear {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December,
}
Example
enum EnumofYear {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December,
}
void main() {
print("JavaTpoint - Dart Enumeration" );
print(EnumofYear.values);
EnumofWeek.values.forEach((v) => print('value: $v, index: ${v.index}'));
}
Output
JavaTpoint - Dart Enumeration
[EnumofYear.January, EnumofYear.February, EnumofYear.March, EnumofYear.April, EnumofYear.May, EnumofYear.June, EnumofYear.July, EnumofYear.August, EnumofYear.September, EnumofYear.October, EnumofYear.November, EnumofYear.December]
value: EnumofYear.January, index: 0
value: EnumofYear.February, index: 1
value: EnumofYear.March, index: 2
value: EnumofYear.April, index: 3
value: EnumofYear.May, index: 4
value: EnumofYear.June, index: 5
value: EnumofYear.July, index: 6
value: EnumofYear.August, index: 7
value: EnumofYear.September, index: 8
value: EnumofYear.October, index: 9
value: EnumofYear.November, index: 10
value: EnumofYear.December, index: 11
Example
enum Process_Status {
none,
running,
stopped,
paused
}
void main() {
print(Process_Status.values);
Process_Status.values.forEach((v) => print('value: $v, index: ${v.index}'));
print('running: ${Process_Status.running}, ${Process_Status.running.index}');
print('running index: ${Process_Status.values[1]}');
}
Output
[Process_Status.none, Process_Status.running, Process_Status.stopped, Process_Status.paused]
value: Process_Status.none, index: 0
value: Process_Status.running, index: 1
value: Process_Status.stopped, index: 2
value: Process_Status.paused, index: 3
running: Process_Status.running, 1
running index: Process_Status.running