CodeBlanks Logo Icon CodeBlanks

Defining enums

Learn to define named constants with enum.

What is an enum?

An enum is a set of named constants. It groups a limited number of options under a single type. For example days of the week, order status, traffic light colors. Grouping constants in an enum instead of writing them one by one makes code readable and safe.

In Dart the definition is: enum Color { red, green, blue }. Each name is a constant; you access it as Color.red. It gives type safety: a function expecting a Color cannot accidentally take a String. The order of the constants follows the order they are written.

Defining an enum

To define an enum you write the enum keyword, then a name and a list of constants inside curly braces. Constants are separated by commas and conventionally start with lowercase. enum Heat { low, medium, high } is a valid definition.

After the definition you can assign a constant to a variable: final h = Heat.medium;. The compiler catches a wrong constant name right away; Heat.tallness would not compile. That is why enum is safer than string constants. The dot also gives you autocomplete when you type the constant name.

Practice Your turn: define a Color enum

Define an enum called Color with constants red, green and blue. In main assign Color.green to a variable and print it.

Starter code

main.dart
void main() {
  // Define a Color enum
  // Assign a constant and print
}

Sample solution

main.dart
enum Color { red, green, blue }

void main() {
  final c = Color.green;
  print(c);
}

Expected output

Color.green

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is enum best suited for?

  • Heavy numeric computation
  • Random text input
  • A limited set of named options Correct answer
  • File operations

Explanation: enum is for a limited set of named options.

2 The enum keyword

Question
____ Color { red, green, blue }
Answer
enum Color { red, green, blue }

Explanation: The enum keyword starts the definition.

3 Match enum

Term Meaning
enum named constants
Color.red a single constant
{ ... } the constant list
enum keyword starts the definition

All lessons in Beginner