0

I want to have a map which saves two types of lists. When I try to add a list with two items into a map, the map gets a list with only one item, although it had two! How can I add the list to the map, without losing any items?

    Map<String, dynamic> habitMap = json.decode(oldJsonString);
    List<HabitBuild> habitBuildList = [];
    List<dynamic> dynamicList = habitMap["habitBuildList"];
    dynamicList.forEach((element) {
      habitBuildList.add(HabitBuild.fromJson(element));
    });
    habitBuildList.add(habitBuild);
    habitMap.putIfAbsent("habitBuildList", () => habitBuildList);
    String jsonString = json.encode(habitMap);

Here what says my debugger: enter image description here

rento
  • 47
  • 1
  • 7
  • 1
    Your code does exactly what is says it does. you loop `habitMap["habitBuildList"]` which has exactly 1 item and add it to `habitBuildList`, then after the loop, you add another `habitBuild` to the `habitBuildList` now you have 2 items in `habitBuildList`. problem? Maybe explain exactly what you want to achieve and the purpose of this code then maybe we can help. – Pierre Apr 08 '22 at 06:13
  • Exactly. The habitBuildList has two items. This list i want to add to my map. But in the map itself the added list has only one item. Although it had two items in it. This is also displayed in the screenshot. – rento Apr 08 '22 at 06:18
  • 1
    `habitMap.putIfAbsent("habitBuildList", () => habitBuildList);` adds `habitBuildList` only if `'habitBuildList'` doesn't already exist in `habitMap`. Did it already have a `List` with only one element? Note that the value of the existing `habitMap['habitBuildList'][0]` entry is a `Map` and *not* a `HabitBuild`, which indicates that this code never added anything. – jamesdlin Apr 08 '22 at 06:40
  • You're my hero. This is the answer – rento Apr 08 '22 at 06:46
  • If you add your comment as an answer, I will mark it as one – rento Apr 29 '22 at 12:35

0 Answers0