Dart: Extension method on enum doesn't work "The method isn't defined for the class" Dart: Extension method on enum doesn't work "The method isn't defined for the class" dart dart

Dart: Extension method on enum doesn't work "The method isn't defined for the class"


You need to give the extension a name.

Dart extensions can be declared without a name, but that just means they are given a fresh private name instead, and therefore the extension is only accessible inside the library where it is declared. You basically never want an extension without a name.

If you give it a public name, then the extension can be imported into other libraries along with the enum.


I found the solution here: Import extension method from another file in Dart

There are two ways:

Solution number 1: Place the extension method in the dart, where it is used.But often it is better the place the extension method in the same file as the correspondig enumeration. So I prefer this:

Solution number 2: Give the extension a name which is different from the enum name. Code:

enum TagVisibility {  public,  shared,  private,}extension TagGerman on TagVisibility {  String get german {    switch(this){      case TagVisibility.public: return "Für alle sichtbar";      case TagVisibility.shared: return "Für alle mit demselben Tag sichtbar";      case TagVisibility.private: return "Nur für mich sichtbar";      default: throw Exception("enum has more cases");    }  }}


You defined as getter:

...String get german {...

but using it as method:

...child: Text('${visibility.german()}'), // doesn't work...

What you should do is to use it as getter:

...child: Text('${visibility.german}'), // this should work...