Home > front end >  Map<int, List<int>> convert to encodable object failed
Map<int, List<int>> convert to encodable object failed

Time:12-20

i am trying to convert a Map<int, List int> to json, so i can save it. Sadly i am getting this Error

E/flutter ( 9386): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'AppState'

I dont understand how i have to change my function

  String bookProgressToJson(Map<int, List<int>> data) =>
  json.encode(Map.from(data).map((k, v) =>
      MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x)))));

any ideas?

CodePudding user response:

JSON only encodes maps with String as the key. See how the thing before the colon is shown as string here: https://www.json.org/json-en.html

So, if you want to encode a Map<int, something> you could convert the int to a String so that you can encode it, and convert it back after decoding it, like this:

import 'dart:convert';

void main() {
  final data = <int, List<int>>{
    0: [1, 2, 3, 4, 5],
    1: [2, 3, 4, 5, 6],
    2: [5, 4, 3, 2, 1],
  };

  final d2 = data.map<String, List<int>>(
    (k, v) => MapEntry(k.toString(), v), // convert int to String
  );

  final j = json.encode(d2);

  final d3 = json.decode(j) as Map<String, dynamic>;

  final d4 = d3.map<int, List<int>>(
    (k, v) => MapEntry(int.parse(k), v.cast<int>()), // parse String back to int
  );
  print(d4);
}

CodePudding user response:

json.encode(data.toString()); works fine

But now i have to redo the progress and save my String as Map<int List>

I tried Map<String, List<int>> emptyFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<int>>(k, List<int>.from(v.map((x) => x))));but this dont work

and my next idea was something like this var dataSp = json["downloadedContent"].split(','); dataSp.forEach( (element) => downloadedContent[element.split(':')[0]] = element.split(':')[1]); but i cant split at , cause all elements are splitted like this.

Perhaps there is a smart and fast solution too.

  • Related