deepMerge method

Map<String, dynamic> deepMerge(
  1. Map<String, dynamic> other
)

Deeply merges another map into this map, recursively combining nested maps.

For example:

{
  'user': {
    'name': 'John',
    'country': 'Italy'
  },
  'active': true
}.deepMerge({
  'user': {
    'name': 'Jane'
  }
})

Results in:

{
  'user': {
    'name': 'Jane',      // Updated value
    'country': 'Italy'   // Preserved from original
  },
  'active': true         // Preserved from original
}

When both maps have the same key:

  • If both values are Map<String, dynamic>, they are recursively merged
  • Otherwise (including Lists, Sets, primitives), the value from other completely replaces the original value

Implementation

Map<String, dynamic> deepMerge(Map<String, dynamic> other) {
  // Create a deep copy to avoid mutating nested structures
  // final thisAsGeneric = this as Map<dynamic, dynamic>;
  // final copied = thisAsGeneric.deepCopy();
  final result = Map<String, dynamic>.from(this);

  for (final entry in other.entries) {
    if (result.containsKey(entry.key) &&
        result[entry.key] is Map &&
        entry.value is Map) {
      // Both are maps, recursively merge them
      final existingMap = Map<String, dynamic>.from(result[entry.key] as Map);
      final newMap = Map<String, dynamic>.from(entry.value as Map);
      result[entry.key] = existingMap.deepMerge(newMap);
    } else {
      // Otherwise replace the value
      result[entry.key] = entry.value;
    }
  }

  return result;
}