[Solved] Concurrent modification during iteration Error in Flutter

In this post, you will learn to solve the "Concurrent modification during iteration" error in Dart or Flutter. This error occurs when you modify Map while iteration, or during the loop, i.e. Add or remove an item from Map during the loop.

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═════════════
The following ConcurrentModificationError was thrown building Builder:
Concurrent modification during iteration: _LinkedHashMap len:3.

This error occurs when you modify Map during iteration, for example, you are not allowed to delete or add items during loop through the loop:

Map values = {
   "a":1,
   "b":2,
   "c":3,
   "d":2
};

values.forEach((key, value) {
   //here if value is 2, I want to print, elese delete
   if(value == 2){
      print("Value is 2");
   }else{
      values.remove(key);
      //error: Concurrent modification during iteration
   }
});

Here, We have tried to delete the item from Map while on loop, and the error occurs. To solve this issue, code like:

Map values = {
   "a":1,
   "b":2,
   "c":3,
   "d":2
};

List<String> toRemove = []; //this is the list of key to delete

values.forEach((key, value) {
   //here if value is 2, I want to print, elese delete
   if(value == 2){
      print("Value is 2");
   }else{
      toRemove.add(key);
   }
});

values.removeWhere((key, value) => toRemove.contains(key));
print(values);
//Output: {b: 2, d: 2}
//Other Items are delete.

Here, we have a blank list of keys to delete items from Map, while on the loop, we list out the key to delete and remove them all after the loop. So, the modification happens after the iteration of the Map.

In this way, you can solve the "Concurrent modification during iteration" error in Dart or Flutter.

No any Comments on this Article


Please Wait...