addOrMerge method

void addOrMerge(
  1. Map<String, Object> source,
  2. String name
)

Adds a new MapPropertySource with the given name, or merges the provided source map into an existing one if a property source with the same name is already present.

This method is designed for dynamic, incremental configuration updates, such as loading layered configuration files, merging environment overrides, or applying runtime-provided settings.

Behavior

  • If no property source with the given name exists:

    • A new MapPropertySource is created containing all key–value pairs from source.
    • It is added with lowest precedence using addLast.
  • If a matching property source does exist:

If source is empty, this method performs no action.

Example

sources.addOrMerge({'debug': 'true'}, 'env');

// If 'env' already exists, keys are merged.
// If not, a new MapPropertySource('env') is added.

Implementation

void addOrMerge(Map<String, Object> source, String name) {
  if (source.isNotEmpty) {
    final resultingSource = <String, Object>{};
    final propertySource = MapPropertySource(name, resultingSource);

    if (containsName(name)) {
      mergeIfPossible(source, resultingSource, name);
      replace(name, propertySource);
    } else {
      resultingSource.addAll(source);
      addLast(propertySource);
    }
  }
}