What is Enums or Enumeration?
In Dart, Enums (short for enumerations) are a special data type used to represent a fixed number of constant values.
Enums allow you to define a set of named constants, known as enumeration constants, within a group.
Syntax:
enum variable_name{
// Insert the data members as shown
member1, member2, member3, ...., memberN
}
Let’s analyze the above syntax:
The enum is the keyword used to initialize enumerated data type.
The variable_name as the name suggests is used for naming the enumerated class.
The data members inside the enumerated class must be separated by the commas.
Each data member is assigned an integer greater than then the previous one, starting with 0 (by default).
Make sure not to use semi-colon or comma at the end of the last data member.
Simple Enums
Defining a simple enum in Dart is easy. You start with the enum
keyword followed by the name of the enum and a list of constant values enclosed in curly braces {}
. Each constant value is separated by a comma.
enum Weekday {
monday,
tuesday,
wednesday,
thursday,
friday
}
void main() {
Weekday today = Weekday.tuesday;
switch (today) {
case Weekday.monday:
print('It\'s Monday');
break;
case Weekday.tuesday:
print('It\'s Tuesday');
break;
case Weekday.wednesday:
print('It\'s Wednesday');
break;
// Handle other weekdays...
default:
print('It\'s not Monday, Tuesday, or Wednesday');
}
}
//Output:
Tuesday
Explanation:
Line 1-6: Defines an enum named
Weekday
with five constants:monday
,tuesday
,wednesday
,thursday
, andfriday
.Line 8-24: Defines the main function where the program execution starts.
Line 9: Declares a variable
today
of typeWeekday
and initializes it withWeekday.tuesday
.Line 11-24: Begins a switch statement to check the value of
today
.Line 12-20: Handles each weekday case individually. If
today
matches a particular weekday, it prints a message indicating the day and then breaks out of the switch statement using thebreak
keyword.Line 22-23: Provides a default case to handle any weekday that is not explicitly listed in the switch statement. If
today
doesn't match any of the specified weekdays, it prints a message indicating that it's not Monday, Tuesday, or Wednesday.
Conclusion
Incorporating simple enums into your Dart applications can lead to cleaner, more understandable code that is easier to maintain and extend.
Enhanced Enums
Enhanced enums in Dart build upon the foundation of traditional enums by allowing developers to add constructors, methods, and properties directly to enum constants.
Enhanced enums in Dart refer to a set of additional features and capabilities.
Which provide more flexibility and functionality compared to traditional enums.
Features of Dart Enhanced Enums
1. Methods and Behaviors:
Enhanced Enums bring the ability to define methods, making enums more than just a collection of values. This opens up opportunities for encapsulating logic within enum elements, enhancing code organization and readability.
enum Status {
pending,
approved,
rejected,
// Method in the Enhanced Enum
String displayStatus() {
return this.toString().split('.').last;
}
}
void main() {
print(Status.pending.displayStatus()); // Outputs: "pending"
}
2. Properties:
With Enhanced Enums, you can attach properties to individual enum values. This can be particularly useful when each enum variant requires additional data.
enum Planet {
mercury,
venus,
earth,
mars,
jupiter,
saturn,
uranus,
neptune,
// Property in the Enhanced Enum
int get order {
return this.index + 1;
}
}
void main() {
print(Planet.earth.order); // Outputs: 3
}
3. Custom Constructors:
Enhanced Enums allow the definition of custom constructors, enabling more dynamic instantiation of enum values.
enum LogLevel {
debug,
info,
warning,
error,
// Custom Constructor in the Enhanced Enum
LogLevel.custom(String customLevel) : this._(customLevel);
final String _value;
const LogLevel._(this._value);
}
void main() {
final customLogLevel = LogLevel.custom("custom");
print(customLogLevel); // Outputs: "custom"
}
Treating Enums Like Classes
Enums are just classes, and enum values are instances of the class. This means that you can apply much of your other knowledge about classes.
Adding Constructors and Properties
Just as classes have constructors and properties, so do enums.
Example:
Here's how we can enhance the enum to behave more like a class by using an extension:
enum TrafficLight {
green,
yellow,
red,
}
// Define an extension for the TrafficLight enum
extension TrafficLightExtension on TrafficLight {
// Method to retrieve the message associated with each enum constant
String get message {
switch (this) {
case TrafficLight.green:
return 'Go!';
case TrafficLight.yellow:
return 'Slow down!';
case TrafficLight.red:
return 'Stop!';
default:
return '';
}
}
}
void main() {
final color = TrafficLight.green;
print(color.message); // Output: Go!
}
In this modification:
We define an extension named
TrafficLightExtension
on theTrafficLight
enum.Inside the extension, we define a getter
message
that returns the message associated with each enum constant.In the
main()
function, we create an instance ofTrafficLight
namedcolor
with thegreen
constant, and then we access itsmessage
property using the extension, which retrieves and prints the message associated with thegreen
constant: "Go!".
By using extensions, we can add methods and properties to enums, making them behave more like classes with additional functionality. This enhances the usability and flexibility of enums in Dart, allowing us to encapsulate behavior within enum constants. However, it's important to note that enums in Dart still have some limitations compared to classes, such as the inability to subclass or have instance fields.