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.
I know I can do it with the map, but this solution doesn't seem safe.
CodePudding user response:
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.
