In this tutorial you will learn about the Dart Enumeration and its application with practical example.
Dart Enumeration
An enumeration is a set of predefined named values, called as members. Enumerations are useful when we want deal with limited set of values for variable. For example you can think of the colors of a traffic light can only be one of three colors– red, yellow or green.
Defining an enumeration
In Dart, enumeration can be declared using the enum keyword followed by a list of the individual members enclosed between pair of curly brackets {}.
Syntax:-
1 2 3 |
enum <enum_name>{ const1, const2, ...., constN } |
Example:-
Let’s define an enumeration for days of week –
1 2 3 4 5 6 7 8 9 |
enum DaysofWeek { Sun, Mon, Tue, Wed, Thu, Fri, Sat } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
enum DaysofWeek{ Sun, Mon, Tue, Wed, Thu, Fri, Sat } void main(){ print("W3Adda - Dart Enumeration"); print(DaysofWeek.values); DaysofWeek.values.forEach((v) => print('value: $v, index: ${v.index}')); } |
Output:-