Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is an enum with string (quoted text) in Dart possible?

I’m a beginner in dart, I need to implement such an enum in dart:

  export enum Something {
        'qwe' = 1,
        'rty' = 2,
        'uio' = 4,
    }

I would like to code and encode the values ​​both ways, what is the best structure for that in dart?

For example, having the variable 4, I would like to get ‘uio’, and in other classes with the string ‘uio’ I would like to get 4.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know I can do it with the map, but this solution doesn’t seem safe.

>Solution :

The best structure is a map. Or two maps, since you want to map both ways.

You are mapping from String to int, and from int to String. That’s two value mappings.

It has nothing to do with enums, which are multiple instances of the same type.

I’m sure you can find some "BiDirectionalMap" out there, but it’s unlikely to be worth it since your mapping doesn’t need to be updated dyamically.
Two constant maps will do:

const somethingMap = {
  'qwe': 1,
  'rty': 2,
  'uio': 4,
};
const somethingReverseMap = {
  1: 'qwe',
  2: 'rty',
  4: 'uio',
};
int something(String code) => somethingMap[code] ?? 
    throw ArgumentError.value(code, "code", "Not a valid code");
String somethingReverse(int value) => somethingReverseMap[value] ?? 
    throw ArgumentError.value(value, "value", "Not a valid value");

Nothing you do will get safer than this. You are switching on the runtime string values, not allowing every string value, so you can’t use the type system.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading