Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a type of enum as an argument in Dart?

Tags:

flutter

dart

I want to have a method that takes a parameter of type enum as a parameter and then operates on it to get all possible values of the enum type, and do some work with each of those values.

I'd be hoping for something like:

Widget foo (EnumType enumType) {
    for(var value in enumType.values) {
        print(value.name);
    }
}

I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a parm, however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error Error: The getter 'name' isn't defined for the class 'Object'. Maybe my only problem is that I don't know how to specify a variable as an EnumType but I haven't been able to find a correct type for this.

like image 654
diarmuid Avatar asked Nov 01 '25 06:11

diarmuid


1 Answers

EnumType.values is the equivalent of an automatically generated static method on EnumType and as such is not part of any object's interface. You therefore will not be able to directly call .values dynamically.

I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a [parameter], however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error

You can use a generic function that restricts its type parameter to be an Enum:

enum Direction {
  north,
  east,
  south,
  west,
}

List<String> getNames<T extends Enum>(List<T> enumValues) =>
    [for (var e in enumValues) e.name];

void main() {
  print(getNames(Direction.values)); // Prints: [north, east, south, west]
}
like image 189
jamesdlin Avatar answered Nov 03 '25 22:11

jamesdlin