I am trying to remove element from nested my by searching the key but I am getting error
Concurrent modification during iteration: Instance of ‘IdentityMap<String, String>’.
void main() {
Map<String, dynamic> nestedMap = {
'key1': 'value1',
'key2': {
'nestedKey1': 'nestedValue1',
'nestedKey2': 'nestedValue2',
},
'key3': {
'nestedKey3': {
'nestedKey4': 'nestedValue3',
},
},
};
String keyToRemove = 'nestedKey2';
// Traverse the nested map and remove the specific key
removeKeyFromNestedMap(nestedMap, keyToRemove);
// Print the updated nested map
print(nestedMap);
}
void removeKeyFromNestedMap(Map<String, dynamic> map, String keyToRemove) {
map.forEach((key, value) {
if (value is Map) {
removeKeyFromNestedMap(value, keyToRemove);
} else if (key == keyToRemove) {
map.remove(key);
}
});
}
2
Answers
The error you are getting is due the map is modified and itrated at the same time. you are looping through the map and the same time you are removing item from it. to counter this issue there are two solutions either
You can’t change a map while iterating it. Having said that, it’s actually okay to try to remove the key from the map even if you don’t know if it’s in it, so you don’t even need to check if the key is in it. So you could do this: