skip to Main Content

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


  1. 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

    1. copy the map in a second map and itertate that map and remove item from the original map. like this:
    
    void removeKeyFromNestedMap(Map map, String keyToRemove) {
      // Create a new map to store the filtered elements
      final filteredMap = Map<String, dynamic>.from(map);
    
      filteredMap.forEach((key, value) {
        if (value is Map) {
          removeKeyFromNestedMap(value, keyToRemove);
        } else if (key == keyToRemove) {
          map.remove(key);
        }
      });
    }
    
    1. or save the key with yourself and remove item from the map when the itretation is completed like this:
    void removeKeyFromNestedMap(Map map, String keyToRemove) {
      String keyc = "";
      map.forEach((key, value) {
        if (value is Map) {
          removeKeyFromNestedMap(value, keyToRemove);
        } else {
          if (key == keyToRemove) {
            keyc = key;
          }
        }
      });
      if (keyc.isNotEmpty) {
        map.remove(keyc);
      }
    }
    
    Login or Signup to reply.
  2. 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:

    void removeKeyFromNestedMap(Map map, String keyToRemove) {
      map.remove(keyToRemove);
      for (var value in map.values) {
        if (value is Map) {
          removeKeyFromNestedMap(value, keyToRemove);
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search