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
1enum UserRole {2 admin,3 editor,4 viewer5}6 7void main() {8 UserRole myRole = UserRole.admin;9 10 // Useful Properties11 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
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
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 Constructor10 const Subscription(this.price, this.description);11 12 // Methods13 bool isExpensive() => price > 10;14}15 16void main() {17 var myPlan = Subscription.premium;18 19 print(myPlan.price); // 9.9920 print(myPlan.description); // All Features21 print(myPlan.isExpensive()); // false22}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
Exercise 1: Create Enum
Create an enum called TrafficLight with values red, yellow, green.
Reveal solutionHide solution
1enum TrafficLight { red, yellow, green }Exercise 2: Switch Logic
Write a switch statement that prints "Stop" if the light is red.
Reveal solutionHide solution
1switch(light) { case TrafficLight.red: print('Stop'); ... }