Add methods or values to enum in dart

2020-02-26 14:02发布

问题:

In java when you are defining an enum you can do something similar to the following. Is this possible in Dart?

enum blah {
  one(1), two(2);
  final num value;
  blah(this.value);
}

回答1:

Starting with Dart 2.6 you can define extensions on classes.

enum Cat {
  black,
  white
}

extension CatExtension on Cat {

  String get name {
    switch (this) {
      case Cat.black:
        return 'Mr Black Cat';
      case Cat.white:
        return 'Ms White Cat';
      default:
        return null;
    }
  }

  void talk() {
    print('meow');
  }
}

Example:

Cat cat = Cat.black;
String catName = cat.name;
cat.talk();

Here's one more live example (uses a constant map instead of a switch): https://dartpad.dartlang.org/c4001d907d6a420cafb2bc2c2507f72c



回答2:

Dart enums are used only for the simplest cases. If you need more powerful or more flexible enums, use classes with static const fields like shown in https://stackoverflow.com/a/15854550/217408

This way you can add whatever you need.



回答3:

Nope. In Dart, enums can only contain the enumerated items:

enum Color {
  red,
  green,
  blue
}

However, each item in the enum automatically has an index number associated with it:

print(Color.red.index);    // 0
print(Color.green.index);  // 1

You can get the values by their index numbers:

print(Color.values[0] == Color.red);  // True

See: https://www.dartlang.org/guides/language/language-tour#enums



回答4:

It may not be "Effective Dart" , I add a static method inside a Helper class ( there is no companion object in Dart) .

In your color.dart file

enum Color {
  red,
  green,
  blue
}

class ColorHelper{

  static String getValue(Color color){
    switch(color){
      case Color.red: 
        return "Red";
      case Color.green: 
        return "Green";
      case Color.blue: 
        return "Blue";  
      default:
        return "";
    }
  }

}

Since the method is in the same file as the enum, one import is enough

import 'package:.../color.dart';

...
String colorValue = ColorHelper.getValue(Color.red);


回答5:

For String returns :

enum Routes{
  SPLASH_SCREEN,
  HOME,
  // TODO Add according to your context
}

String namedRoute(Routes route){
  final runtimeType = '${route.runtimeTypes.toString()}.';
  final output = route.toString();
  return output.replaceAll(runtimeType, "");
}


标签: dart