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

Time:04-12

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.

CodePudding user response:

The problem with enums is that they can't be passed as a parameter, what you can do instead is that pass all the values and then extract the name from the toString method.

void printEnumValues<T>(List<T> values){
  for(var value in values){
    final name = value.toString().split('.')[1];
    print(name);
  }
}

Also I would recommend you look into freezed union classes as that might allow you an alternative approach towards the problem you're trying to solve.

CodePudding user response:

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]
}
  • Related