Encode Map with Enum to JSON

Issue

I want to encode my Map to a json. It looks like this:

Map<MyEnum, int> map = {type: limit};

Where MyEnum is an enum. A simple json.encode(map) won’t work as it does not know how to serialize the enum class I guess.

The error message is:

Unhandled Exception: Converting object to an encodable object failed: _LinkedHashMap len:1

How can I manage to serialize this map to a json?

Solution

You could create an extension on your enum to convert it to a String then convert your map to a Map<String, int> so it will be encoded correctly:

import 'dart:convert';

enum MyEnum { type }

extension MyEnumModifier on MyEnum {
  String get string => this.toString().split('.').last;
}

void main() {
  Map<MyEnum, int> map = {MyEnum.type: 10};
  Map<String, int> newMap = {};
  
  map.forEach((key, value) =>
    newMap[key.string] = value);
  
  final json = jsonEncode(newMap);
  print(json);
}

Output

{"type":10}

Answered By – Guillaume Roux

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.