Enumeration in Dart explanation with example

Enumeration in dart :

Enumeration is an user defined list of constants values. This is a class and also known as enums or enumerated types. Enums are normally used in switch-case blocks. If you are familiar with enums in any other programming languages like Java, enums in Dart is similar to that.

In this post, I will show you how to define enums in dart with examples.

Definition :

Keyword enum is used to define an enumeration. It is defined as like below :

enum EnumName{ list of enums }

EnumName.{name} is used to access one enum value. The below examples will make it more clear.

Accessing index and values :

Each enum values has an index starting from 0. The first value has index 0, second has index 1 etc. We can use the getter property index to access get this position.

Dart also provides one values constant property to get a list of all values of that enum.

Let’s consider the below program :

enum WeekDays { SUN, MON, TUES, WED, THURS, FRI, SAT }

void main() {
  print('Index of ${WeekDays.SUN} : ${WeekDays.SUN.index}');
  print('Index of ${WeekDays.MON} : ${WeekDays.MON.index}');
  print('Index of ${WeekDays.TUES} : ${WeekDays.TUES.index}');
  print('Index of ${WeekDays.WED} : ${WeekDays.WED.index}');
  print('Index of ${WeekDays.THURS} : ${WeekDays.THURS.index}');
  print('Index of ${WeekDays.FRI} : ${WeekDays.FRI.index}');
  print('Index of ${WeekDays.SAT} : ${WeekDays.SAT.index}');
  print('Values ${WeekDays.values}');
}

It will print the below output :

Index of WeekDays.SUN : 0
Index of WeekDays.MON : 1
Index of WeekDays.TUES : 2
Index of WeekDays.WED : 3
Index of WeekDays.THURS : 4
Index of WeekDays.FRI : 5
Index of WeekDays.SAT : 6
Values [WeekDays.SUN, WeekDays.MON, WeekDays.TUES, WeekDays.WED, WeekDays.THURS, WeekDays.FRI, WeekDays.SAT]

Dart enumeration index values

values returns one list. So, we can use one list variable to store these values.

Enums with switch case :

enums are mostly used in switch case statements. For example :

enum Values { ONE, TWO, THREE }

void main() {
  var currentValue = Values.THREE;

  switch (currentValue) {
    case Values.ONE:
      print("One");
      break;
    case Values.TWO:
      print("Two");
      break;
    case Values.THREE:
      print("Three");
      break;
  }
}

It will print the value based on the currentValue. Note that we need to handle all enum’s value if we don’t use default case. It will show one compile time error.

Dart enum switch

Similar tutorials :