Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart, Mapping Enum to a string [duplicate]

Tags:

flutter

dart

I'm using the following code to have enum values and a corresponding string associated with it. I was wondering if there's a simpler way to accomplish this?

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

    }
  }  

}
like image 843
Miguel Dey Avatar asked May 01 '26 20:05

Miguel Dey


1 Answers

Since Dart 2.15 you can get the string by using .name property:

print(StyleType.casual.name); // => 'casual'
like image 193
Dartist Avatar answered May 04 '26 09:05

Dartist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!