Dart Enum constants

Enum alias Enumeration is a new custom type introduced in Dart and used to store a fixed group of constants.

Syntax: Enumeration is declared using the enum keyword.

enum EnumerationName{
    //constants separated by a comma
}

enum is a keyword. EnumerationName is the Name of the Enumeration type. Constants are separated by a trailing comma.

Here is an Enum example

enum Status {initial, pending, loading, completed }

Each enum constant always starts with index=0

Properties:

index: Returns index value for a given enum constant. name: returns constant name values: return list of Enum constants

void main() {
  print(Status.initial.index); //0
  print(Status.initial.name); // initial
  print(Status.initial.name.runtimeType); //String
}

enum Status { initial, pending, loading, completed }

Output:

0
initial
String
[Status. initial, Status. pending, Status.loading, Status. completed]

How to use enum in the switch statement

You can write a case statement for each enum constant and the default case is executed if no match is found for the switch expression.

void main() {
  var status = Status.completed;

  switch (status) {
    case Status.initial:
      print('initial status');
      break;
    case Status.pending:
      print('pending status');
      break;
    case Status.loading:
      print('loading status');
      break;
    case Status.completed:
      print('completed status');
      break;
    default:
      print(status);
  }
}

enum Status { initial, pending, loading, completed }

Important points:

  • Enum constants are compiled time constants.
  • Subclass an enum is not possible
  • Enum class is not created with new or normal object creation