'How to make toMap and fromMap method for Enums class dart flutter?
I used an enum variable in a class. Now I want to implement the toMap and fromMap methods for the class.
enter code here
enum ColorNumber { inc, dec, none }
class CounterState extends Equatable {
int value;
ColorNumber ColorNumber;
CounterState({this.value, this.colorNumber});
@override
List<Object> get props => [value, colorNumber];
Map<String, dynamic> toMap() {
return {
'value': value,
'colorNumber': colorNumber.toMap(), //error to toMap
};
}
factory CounterState.fromMap(Map<String, dynamic> map) {
return CounterState(
value: map['value'],
none: ColorNumber.fromMap(map['colorNumber']), //error to fromMap
);
}
}
Solution 1:[1]
Simple store the enum as int representing thier position.
See below
Map<String, dynamic> toMap() {
return {
'value': value,
'colorNumber': colorNumber.index,
};
}
factory CounterState.fromMap(Map<String, dynamic> map) {
int val = map['colorNumber'];
return CounterState(
value: map['value'],
colorNumber: ColorNumber.values[val],
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nikhil Badyal |