mergeWith method

Map<String, Map> mergeWith(
  1. Map<String, Map> other
)

Merges two maps of type Map<String, Map> into a new map, combining entries with matching keys.

For each matching key, fields from the other map will override or add to the corresponding inner map from the current map (this). If a key exists only in other, it will be added to the resulting map.

This function is useful when combining configuration maps (e.g., settings with localized labels).

Returns a new Map<String, Map> that represents the merged structure.

Example:

final settings = {
  'tasks': {'type': 'agent', 'icon': 'add'},
};

final i18n = {
  'tasks': {'title': 'Tasks'},
  'goals': {'title': 'Goals'},
};

final merged = settings.mergeWith(i18n);
print(merged);
// Output:
// {
//   'tasks': {'type': 'agent', 'icon': 'add', 'title': 'Tasks'},
//   'goals': {'title': 'Goals'},
// }

Implementation

Map<String, Map> mergeWith(Map<String, Map> other) {
  final Map<String, Map> result = {};

  forEach((key, value) {
    final Map merged = Map.from(value);

    if (other.containsKey(key)) {
      merged.addAll(other[key]!);
    }

    result[key] = merged;
  });

  other.forEach((key, value) {
    if (!containsKey(key)) {
      result[key] = Map.from(value);
    }
  });

  return result;
}