【问题标题】:Dart, Mapping Enum to a string [duplicate]Dart,将枚举映射到字符串[重复]
【发布时间】:2022-03-06 23:22:13
【问题描述】:

我正在使用以下代码来获取枚举值和与之关联的相应字符串。我想知道是否有更简单的方法来实现这一点?

enum StyleType {
  casual,
  chic,
  urban,
  vintage,
  punk,
}

class Style{  
  final StyleType type;

  Style(this.type);  
  
  @override
  String toString() {
      switch (type) {
      case StyleType.casual:
        return 'Casual';
      case StyleType.chic:
        return 'Chic';
      case StyleType.punk:
        return 'Punk';
      case StyleType.urban:
        return 'Urban';
      case StyleType.vintage:
        return 'Vintage';

    }
  }  

}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    从 Dart 2.15 开始,您可以使用 .name 属性获取字符串:

    print(StyleType.casual.name); // => 'casual'
    

    【讨论】:

      【解决方案2】:

      这是一个简单的方法

      void main() {
        
        print(test.a.toString().split(".")[1]);
        }
      
      enum test {a,b}
      

      这将输出a

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-09
        • 2019-01-29
        • 1970-01-01
        • 1970-01-01
        • 2011-04-14
        • 2012-01-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多