In Dart, an enum is a special class used to represent a fixed set of constant values. It is a type of data structure that allows you to define a set of named constants, which are immutable and can be used to represent a fixed number of possible values. For example, you might use an enum to represent the days of the week or the states of a system.
Defining an Enum
To define an enum in Dart, use the enum keyword followed by the enum name and its values. Each value is separated by commas and enclosed in curly braces. Here's a simple example:
dartenum Color { red, green, blue }
In this example, Color is the enum type, and red, green, and blue are the constant values. Enums are implicitly final, meaning their values cannot be changed after initialization.
Using an Enum
Enums can be used in your code by referencing their values. For instance, you can declare a variable of the enum type and assign it one of the values:
dartvoid main() { Color myColor = Color.red; print('My favorite color is $myColor'); // Output: My favorite color is red }
You can also use enums in conditional statements or switch expressions to handle different cases:
dartvoid checkColor(Color color) { switch (color) { case Color.red: print('It's red'); break; case Color.green: print('It's green'); break; case Color.blue: print('It's blue'); break; } }
Key Points
- Enums are immutable: Once defined, their values cannot be altered.
- Enums are type-safe: You cannot assign a value outside the defined set, which helps prevent runtime errors.
- Enums can have associated data: You can add methods or properties to enum values using the
constconstructor or by defining them in the enum body.
For example, here's an enum with additional data:
dartenum Status { success(message: 'Operation completed'), error(message: 'An error occurred'); final String message; const Status({required this.message}); }
This allows you to handle different states with context-specific information.
Best Practices
- Use enums for discrete sets of values where the number of possibilities is fixed and known at compile time.
- Avoid using enums for dynamic or variable data, as they are not designed for that purpose.
- Prefer enums over
intorStringfor type safety in scenarios like state management or configuration.
By following these guidelines, you can leverage Dart's enum system to write clean, maintainable code with clear semantics.