Home > other >  How to encode this map Map<int, List<int>>?
How to encode this map Map<int, List<int>>?

Time:01-20

Hi I am having problems encoding this kind of map: Map<int, List<int>> blocksMap any suggestions how to do it? cause json.encode(blocksMap) gives an error Converting object to an encodable object failed: _LinkedHashMap

This is the example of data i'm trying to encode:

Map<int, List<int>> blocksMap:

{
0: [18, 117, 26, 200, 4, 30, 43, 110],
1: [18, 117, 26, 200, 4, 30, 43, 110], 
2: [18, 117, 26, 200, 4, 30, 43, 110], 
3: [18, 117, 26, 200, 4, 30, 43, 110], 
4: [18, 117, 26, 200, 4, 30, 43, 110], 
5: [18, 117, 26, 200, 4, 30, 43, 110], 
6: [18, 117, 26, 200, 4, 30, 43, 110], 
7: [18, 117, 26, 200, 4, 30, 43, 110], 
8: [18, 117, 26, 200, 4, 30, 43, 110], 
9: [18, 117, 26, 200, 4, 30, 43, 110], 
10: [18, 117, 26, 200, 4, 30, 43, 110], 
11: [18, 117, 26, 200, 4, 30, 43, 110]
}

Suggestions how to encode this map would be great, Thanks!

CodePudding user response:

You can convert your map to a Map of String and List of Strings

  final Map<String, List<int>> blocksMapOfIntToString = {
    for (var item in blocksMap.entries) '${item.key}': item.value,
  };

Then encode

  final encoded = jsonEncode(blocksMapOfIntToString);

And whenever you need your data, you decode

  final decoded = jsonDecode(encoded);

Then convert back

  final Map<int, List<int>> blocksMapOfStringToInt = {
    for (var item in decoded.entries)
      int.parse(item.key): List<int>.from(item.value),
  };
  •  Tags:  
  • Related