Enumerations in Dart Programming


An enumeration is a set of predefined values. These values are known as members. They are useful when we want to deal with a limited set of values for the variable. For example, you can think of the number of days in a week - Monday, Tuesday, Wednesday etc.

An Enumeration can be declared using the enum keyword.

Syntax

enum <enum_name> {
   const1,
   const2,
   ….
   constN
}

Let's define an enumeration for the number of colors in a traffic light −

enum TrafficLights {
   Red,
   Green,
   Yellow
}

Now, let's see how we can make use of an enumeration in a Dart program.

Example

Consider the example shown below −

 Live Demo

enum TrafficLights {
   Red,
   Green,
   Yellow
}

void main(){
   print(TrafficLights.values);
   TrafficLights.values.forEach((x) => print('value : $x'));
}

Output

[TrafficLights.Red, TrafficLights.Green, TrafficLights.Yellow]
value : TrafficLights.Red
value : TrafficLights.Green
value : TrafficLights.Yellow

Updated on: 21-May-2021

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements