Back to quest
Control Flow & FunctionsLevel 21 / 32

Enums

Defining and using Enumerated types in Dart

Enums (Enumerations) are a special way to define a collection of named constant values. They are perfect for representing a fixed set of options, like days of the week, user roles, or connection states.

1. Basic Enums

Enums allow you to define a restricted list of values. Behind the scenes, they are special classes where you only have a fixed number of instances.

Defining User Roles

example.dart
1enum UserRole {
2 admin,
3 editor,
4 viewer
5}
6 
7void main() {
8 UserRole myRole = UserRole.admin;
9
10 // Useful Properties
11 print(myRole.index); // 0 (The position in the list)
12 print(myRole.name); // "admin" (The string name)
13}

HintUsing enums prevents "Magic String" bugs (e.g., typing "Admin" instead of "admin").

2. Iterating Enums

You can access a list of all possible values using .values. This is useful for building UI, like a dropdown menu.

Looping Values

example.dart
1enum Color { red, green, blue }
2 
3void main() {
4 List<Color> allColors = Color.values;
5 
6 for (var color in allColors) {
7 print(color.name);
8 }
9}

HintColor.values returns a list [Color.red, Color.green, Color.blue].

3. Enhanced Enums (Properties & Methods)

Since Dart 2.17, Enums are supercharged. They can have final fields, constructors, and methods, just like classes.

Powerful Enums

example.dart
1enum Subscription {
2 free(0, 'Basic Features'),
3 premium(9.99, 'All Features'),
4 family(14.99, 'Shared Access'); // Semicolon required here!
5 
6 final double price;
7 final String description;
8 
9 // Constant Constructor
10 const Subscription(this.price, this.description);
11 
12 // Methods
13 bool isExpensive() => price > 10;
14}
15 
16void main() {
17 var myPlan = Subscription.premium;
18 
19 print(myPlan.price); // 9.99
20 print(myPlan.description); // All Features
21 print(myPlan.isExpensive()); // false
22}

HintThis effectively replaces the old "Helper Class" pattern. All the logic lives right inside the Enum.

Loot collected

Key takeaways
  • Use Enums for fixed lists of options (Status, Role, Category).
  • Enums prevent spelling mistakes compared to using simple Strings.
  • Always use Enums with Switch statements to handle logic cleanly.
  • Enhanced Enums can hold extra data like integers or strings.

Side quests

Practice exercises

1

Exercise 1: Create Enum

Create an enum called TrafficLight with values red, yellow, green.

Reveal solution
solution.dart
1enum TrafficLight { red, yellow, green }
2

Exercise 2: Switch Logic

Write a switch statement that prints "Stop" if the light is red.

Reveal solution
solution.dart
1switch(light) { case TrafficLight.red: print('Stop'); ... }
Party chat

Comments