Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing enum type as argument in Dart 2

Tags:

enums

dart

Just like passing class type as argument to method I want to pass enum, as I want to write a general method which operates on enum.

I tried:

  void foo(E):
    print(E.values[0])

but it doesn't work.

Is there a way?

like image 770
Harsh Bhikadia Avatar asked Sep 03 '18 17:09

Harsh Bhikadia


People also ask

Can enum implement interface in DART?

Enums are still restricted, you cannot implement the interface other than by creating an enum .

How do you extend an enum in darts?

In the full example, which you can see in CodePen above, the enum is extended with four methods: displayTitle() , displayColorChangeText() , color() , and getRandomSelectedColor() .


1 Answers

This might work for you

typedef EnumValues<T> = List<T> Function();

void main() {
  foo<E1>(() => E1.values);
  foo<E2>(() => E2.values);
}

enum E1 { a, b }
enum E2 { c, d }

void foo<T>(EnumValues<T> valuesFn) {
  var values = valuesFn();
  for (var v in values) {
    print(v);
  }
}

See comments - shorter version

void main() {
  foo<E1>(E1.values);
  foo<E2>(E2.values);
}

enum E1 { a, b }
enum E2 { c, d }

void foo<T>(List<T> values) {
  for (var v in values) {
    print(v);
  }
  print(values[0]);
}
like image 82
Günter Zöchbauer Avatar answered Nov 15 '22 08:11

Günter Zöchbauer