THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
Enum in Dart introduced Generics to constants.
Generics can be defined during enum declaration, Generics helps developer to avoid type safety errors.
This tutorials explains multiple things
Defined enum with generic and accepts String integer values
enum EmployeeEnum<T> {
name<String>(),
salary<int>();
}
void main() {
print(EmployeeEnum.name.runtimeType); // EmployeeEnum<String>
print(EmployeeEnum.salary.runtimeType); // AniEmployeeEnummal<int>
}
Another example, Generics are of the type that extends Objects. It accepts any type and added value with the constructor.
You can access the value of an enum using Enum.value
enum Week<T extends Object> {
number<int>(1),
name<String>('sunday'),
isWorking(false);
const Week(this.value);
final T value;
}
void main() {
Week week = Week.name;
print(week.name.runtimeType); // String
print(week.value); // sunday
}
Enum can be used as a constrained generic type to a class as a given example. the class accepts Enum constants only.
Here is an example
class WorkingDay<T extends Enum> {}
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
void main() {
WorkingDay<WEEK> working = WorkingDay<WEEK>();
print(working.runtimeType);
print(working.toString());
}
Output:
WorkingDay<WEEK>
An instance of 'WorkingDay<WEEK>'
This example explains passing a Generic type enum constant to a function.
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
List<String> getEnumNames<T extends Enum>(List<T> values) =>
[for (var e in values) e.name];
void main() {
print(getEnumNames(WEEK.values));
}
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts