Search code examples
flutterdart

Flutter Error ConcurrentModificationError (Concurrent modification during iteration: Instance(length:0) of '_GrowableList'.)


I have this code that throws ConcurrentModificationError (Concurrent modification during iteration: Instance(length:0) of '_GrowableList'.) error but I am modifying a copy of the map not the map itself. I have a database that loos something like this:

Map tasks = {
"10-10-2011": [Event(title:"Hello", done: true), Event(), Event()], 
"10-05-2011": [Event(title:"Hello123", done: false), Event(), Event()], 

}

Here is my code with the error that stops at the Value

void addUnfinishedTasks() {
    Map tasksCopy = tasks;
    String today = DateTime.now().toString().substring(0, 10);
    tasksCopy.forEach((key, value) {
      if (key != today) {
        for (Event task in value) {
          if (!task.done) {
            tasks[key].remove(task);
            if (tasks.containsKey(today)) {
              tasks[today].add(task);
            } else {
              tasks[today] = [task];
            }
          }
        }
      }
    });
  updateDataBase();
  }`

I tried adding other copies of the maps and lists also created copy of the value, but nothing worked.


Solution

  • The tasks having List values, and on dart, object of an instance is passed by reference. You can recreate the List for tasksCopy

    You can replace Map tasksCopy = tasks; with

        Map<String, List<Event>> tasksCopy = Map.fromEntries(tasks.entries.map(
          (e) => MapEntry(e.key, e.value.toList()),
        ));