'Parse enum from json

I have an enum

enum Mode { standard, relative, fixed }

extension ModeMap on Mode {
  static const valueMap = {
    Mode.standard: "standard",
    Mode.relative: "relative",
    Mode.fixed: "fixed",
  };
  String? get value => valueMap[this];
}

And a model using this enum with a method fromJson:

class Settings {
  Mode mode;
  String name;

  Settings({
    required this.mode,
    required this.name,
  });

  Settings.fromJson(Map<String, dynamic> json)
      : mode = Mode[json['Mode'].toString()] as Mode,
        name = json['Name'],


  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['Mode'] = mode.value;
    data['Name'] = name;
    return data;
  }
}

However, it seems that I can't transform the values from json to my enum this way. What is the proper way to do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source