Why This Happens
In Dart, modifying a list (adding or removing elements) while iterating over it with a for-in loop causes a ConcurrentModificationError. You should iterate over a copy of the list or collect items to remove and process them after the loop.
The Problem
final items = [1, 2, 3, 4, 5];
for (final item in items) {
if (item.isEven) {
items.remove(item); // Modifying during iteration!
}
}The Fix
final items = [1, 2, 3, 4, 5];
items.removeWhere((item) => item.isEven);Step-by-Step Fix
- 1
Identify the error
Look at the error message: Concurrent modification during iteration. This means the collection was changed while being iterated.
- 2
Find the cause
Check for-in loops where add() or remove() is called on the same list being iterated.
- 3
Apply the fix
Use removeWhere(), iterate over a copy with .toList(), or collect changes and apply them after the loop.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free