{

Enum Generics create, constrain type, and pass to a function in Dart | Flutter By Example


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

  • How to create the type of a generic enum in Dart
  • Constrain a generic type to an Enum
  • Pass a Generic Enum argument to a method

Create a Generic Type Object Enum

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 Object. 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
}

Constrain a generic type to an Enum in Dart

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>'

Pass a Generic Enum argument to a method

This example explains about passing a Generic type enum constant to an 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));
}
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.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.