Enums in Dart

What are Enums?

The enum is to represent a fixed number of constant values which lead to readable or easily maintainable code.

Declare enumerated types:

Use enum keyword to declare enumerated types

The following code snippet shows how to declare enums.

enum Gender {
  Female,
  Male,
}

Get values from enum

Use the enums values constant.

The following code snippet shows how to get values from enum.

main() {

  var gender = Gender.values;

  print(gender.runtimeType); // List<Gender>
}

Enums are integer indexed constant values

By default enums are integer indexed constant values. Zero-based index the first value has index 0, and the second value has index 1

The following code snippet shows how to get index of enum.

main() {
  print(Gender.Male.index);// 1
}

Use enums in switch statements

You can use enums in switch statements,

The following code snippet shows how to use enums in switch statements.

var gender = Gender.Female;

  switch (gender) {
    case Gender.Female:
      print('Female Candidate');
      break;
    case Gender.Male:
      print('Male Candidate');
      break;
    default:
      print(gender);
  }

Note: You’ll get a warning if you don’t handle all of the enums values: