Home > Mobile >  How to set the type of a generic enum in Dart
How to set the type of a generic enum in Dart

Time:06-29

Given the enum below:

enum Animal<T> {
  cow,
  goat;
}

How do I set the type?

If I do this:

void main() {
  final animal = Animal.cow;
}

Dart infers the type of animal to be Animal<dynamic>. However, I'm not able to set the type with any of the following ways:

// The static member 'cow' can't be accessed on a class instantiation.
final animal = Animal<int>.cow;

// `animal` is inferred to be `dynamic`, not `Animal<int>`.
final animal = Animal.cow<int>;

Of course, I'm not using the type anywhere, but this is the simplest example I can think of to demonstrate my question. How would I set the type to int?

CodePudding user response:

Enum values must be constant so the generic needs to be specified as part of initializing the enum values inside the enum definition.

So something like this:

enum Animal<T> {
  cow<String>(),
  goat<int>();
}

void main() {
  print(Animal.cow.runtimeType); // Animal<String>
  print(Animal.goat.runtimeType); // Animal<int>
}
  • Related