Home > Net >  Where is "values" defined in a List of enum?
Where is "values" defined in a List of enum?

Time:03-27

I have an enum and I can use MyColors.values on it but where this values is defined?

enum MyColor {
  red,
  blue,
  green,
}

enum MyNumbers {
  one,
  two,
  three,
}

void main() {
  getNames(MyColor.values);
  getNames(MyNumbers.values);
}

List<String> getNames(List<Enum> enums) {
  return enums.values.map((e) => e.name).toList(); // Error
}

How can I then use values myself?

CodePudding user response:

enum MyColor { red, blue, green } creates a special MyColor Enum class and creates compile-time constant instances of it named red, blue, and green. values is essentially an automatically generated static member.

List<String> getNames(List<Enum> enums) {
  return enums.values.map((e) => e.name).toList(); // Error
}

Your enums parameter is a List, and List does not have a value member. The callers of getNames already passed the list of Enum values. You want:

List<String> getNames(List<Enum> enums) {
  return enums.map((e) => e.name).toList();
}

or:

List<String> getNames(List<Enum> enums) {
  return [for (var e in enums) e.name];
}

what is MyColor, is this an Enum (no), is this a List<Enum>, again no?

MyColor itself is a Type, just like int or double or String or List.

MyColor.red is a compile-time constant instance of a MyColor. MyColor.red is MyColor and MyColor.red is Enum are both true.

This is not fundamentally different from:

class Base {}
class Derived extends Base {}

Derived and Base are Type objects. Derived is Base is false (a Type object is not an instance of Base). However, Derived() is Base is true.

  • Related