Add methods or values to enum in dart

前端 未结 8 966
刺人心
刺人心 2020-12-14 05:21

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 valu         


        
8条回答
  •  情歌与酒
    2020-12-14 06:06

    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);
    

提交回复
热议问题