How to add Methods or Values to Enums in Dart | Flutter By Example
How to add methods to Enum in Dart using Extension
Dart 2.6 version, Extensions are added to classes, and Enum adds extra features.
Defined Enum class as given below
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Next, Add a method to Enum using the extension feature as given below Declare and place this extension in the same class where Enum is defined.
extension WeekExtension on WEEK {
bool get isWeekend {
switch (this) {
case WEEK.SUNDAY:
return true;
case WEEK.SATURDAY:
return true;
default:
return false;
}
}
}
In the extension, Added isWeekend method that checks given Enum is weekend or not. Used switch case expression comparison with Enum constants.
The main method, Defined Enum constant, calls enum method similar to class methods.
WEEK sat = WEEK.SATURDAY;
print(sat.isWeekend); //true
Here is an example of Dart Enum methods extension example
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
extension WeekExtension on WEEK {
bool get isWeekend {
switch (this) {
case WEEK.SUNDAY:
return true;
case WEEK.SATURDAY:
return true;
default:
return false;
}
}
}
void main() {
WEEK sat = WEEK.SATURDAY;
WEEK mon = WEEK.MONDAY;
print(sat.isWeekend); //true
print(mon.isWeekend); // false
}
How to add Arguments or values to Enum in Dart
You can add an argument to Enum since the dart 2.7 version.
To add arguments to Enum in Dart
- First, Make sure that the dart version is 2.7 in pubspec.yaml
- Declare final properties or variables to Enum declaration
- Define Enum with the constructor of variables.
- Define Enum constants with values
- You can access Enum properties Enum object followed by a dot(.) and property name.
Here is an example to pass parameters to the Enum object.
enum WEEKEND {
SATURDAY("saturday", 1),
SUNDAY("sunday", 1);
const WEEKEND(this.name, this.value);
final String name;
final int value;
}
void main() {
WEEKEND sat = WEEKEND.SATURDAY;
print(sat.toString()); //WEEK.MONDAY
print(sat.name); // zero
print(sat.value); // WEEK
}
Conclusion
Enum is similar to classes in terms of defining properties and methods. You can add extension methods.