What are Enums?
Enums (short for enumerations) are a way to define a set of named constants. They are useful when you have a fixed set of related values, like days of the week, status codes, or user roles. In Dart, enums are more powerful than in many other languages – since Dart 2.17, you can create enhanced enums that have fields, constructors, methods, and can even implement interfaces.
Simple Enum
The simplest enum is defined using the enum keyword followed by the name and a list of constant values.
Enum Properties
Every enum has a few built‑in properties:
.name– returns the string name of the enum value (e.g.,'pending').
.index– returns the zero‑based index of the enum value.
.values– returns a list of all enum values (of typeList<Enum>).
Enums in Switch Statements
One of the most common uses of enums is in switch statements. Since enums have a finite set of values, you can easily handle all cases without a default (but it's good practice to include default or handle all cases).
Enhanced Enums (Dart 2.17+)
With Dart 2.17, enums can have constructors, fields, and methods. This makes them much more powerful and allows you to attach additional data to each enum value.
Enhanced Enum with Methods
You can add methods to enums, including getters, setters (though not recommended), and even implement interfaces.
Enums Implementing Interfaces
Enhanced enums can implement interfaces, allowing them to behave polymorphically.
Common Mistakes
- Using
conston enum instances: Enhanced enums requireconstconstructors. Always mark the constructor asconst.
- Using
- Forgetting to handle all cases in a switch: With simple enums, it's okay to use a default; with enhanced enums, you can still use a default, but it's better to cover all cases.
- Over‑engineering simple enums: If you just need a fixed set of names, a simple enum is enough. Use enhanced enums only when you need extra data or behaviour.
Best Practices
- Use enums when you have a fixed, known set of values.
- Prefer enums over string constants for type safety.
- In switch statements, handle all enum values to avoid missing cases (the analyzer can help with exhaustiveness checking).
- For enhanced enums, keep fields
finaland constructorsconstto maintain immutability.
- For enhanced enums, keep fields
Complete Example
Key Takeaways
- Enums define a fixed set of named constants.
- Simple enums are defined with
enum Name { value1, value2 }.
- Simple enums are defined with
- Use
.name,.index, and.valuesto get information about enum values.
- Use
- Enhanced enums (Dart 2.17+) can have fields, constructors, methods, and implement interfaces.
- Enhanced enums must use
constconstructors and all fields must befinal.
- Enhanced enums must use
- Enums are perfect for status codes, roles, categories, and other fixed sets.