Dart How to get the “value” of an enum

后端 未结 15 2047
野的像风
野的像风 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:09

    Dart 2.7 comes with new feature called Extension methods. Now you can write your own methods for Enum as simple as that!

    enum Day { monday, tuesday }
    
    extension ParseToString on Day {
      String toShortString() {
        return this.toString().split('.').last;
      }
    }
    
    main() {
      Day monday = Day.monday;
      print(monday.toShortString()); //prints 'monday'
    }
    

提交回复
热议问题