Search code examples
dartenumsextension-methods

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


basend this Question I created an enum in dart with an extension methode:

enum TagVisibility {
  public,
  shared,
  private,
}

extension 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");
    }
  }
}

But I get the error Error: The method 'german' isn't defined for the class 'TagVisibility'. when I try to call this extension method:

import 'package:prototype/models/visibility.dart';
...
 DropdownButton<TagVisibility>(
          hint: Text("Wähle die Sichtbarkeit für diesen Tag"),
          value: _visibility ?? _visibilityDefault,
          onChanged: (visibility) {
            setState(() {
              _visibility = visibility;
            });
          },
          // items: List<DropdownMenuItem<TagVisibility>>(
          items: TagVisibility.values.map((visibility) => DropdownMenuItem(
            value: visibility,
            child: Text('${visibility.german()}'), // doesn't work
            // child: Text('${visibility.toString()}'), // works, but I want the custom messages.
          ),
          ).toList(),
        ),

I have absolutly no idea what I did wrong here. Can you please explain me how I can get this working? Thx!


Solution

  • 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 file 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");
        }
      }
    }