{

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


 Enum Generics create, constrain type, and pass to a function  dart or flutter

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

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 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));
}
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.





Related posts

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not