Dart How to get the “value” of an enum

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

    Sadly, you are correct that the toString method returns "day.MONDAY", and not the more useful "MONDAY". You can get the rest of the string as:

    day theDay = day.MONDAY;      
    print(theDay.toString().substring(theDay.toString().indexOf('.') + 1));
    

    Hardly convenient, admittedly.

    If you want to iterate all the values, you can do it using day.values:

    for (day theDay in day.values) {
      print(theDay);
    }
    

提交回复
热议问题