Dart How to get the “value” of an enum

后端 未结 15 1851
野的像风
野的像风 2020-12-29 00:50

Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it. I need to get the value of the enum as

15条回答
  •  被撕碎了的回忆
    2020-12-29 01:29

    My approach is not fundamentally different, but might be slightly more convenient in some cases:

    enum Day {
      monday,
      tuesday,
    }
    
    String dayToString(Day d) {
      return '$d'.split('.').last;
    }
    

    In Dart, you cannot customize an enum's toString method, so I think this helper function workaround is necessary and it's one of the best approaches. If you wanted to be more correct in this case, you could make the first letter of the returned string uppercase.

    You could also add a dayFromString function

    Day dayFromString(String s) {
      return Day.values.firstWhere((v) => dayToString(v) == s);
    }
    

    Example usage:

    void main() {
      Day today = Day.monday;
      print('Today is: ${dayToString(today)}');
      Day tomorrow = dayFromString("tuesday");
      print(tomorrow is Day);
    }
    

提交回复
热议问题