compare static method

MapChanges compare(
  1. Map oldMap,
  2. Map newMap
)

Compares two maps and returns different types of changes between them

Implementation

static MapChanges compare(Map oldMap, Map newMap) {
  final result = {
    // Keys present in newMap but not in oldMap
    'added': <String>{},
    // Keys present in oldMap but not in newMap
    'removed': <String>{},
    // Keys present in both maps but with different values
    'modified': <String>{},
    // Keys present in both maps with identical values
    'unchanged': <String>{},
  };

  // Find added and modified keys
  newMap.forEach((key, newValue) {
    if (!oldMap.containsKey(key)) {
      result['added']?.add(key);
    } else {
      final oldValue = oldMap[key];
      if (isDifferent(oldValue, newValue)) {
        result['modified']?.add(key);
      } else {
        result['unchanged']?.add(key);
      }
    }
  });

  // Find removed keys
  for (var key in oldMap.keys) {
    if (!newMap.containsKey(key)) {
      result['removed']?.add(key);
    }
  }

  final added = result["added"]!.toList();
  final removed = result["removed"]!.toList();
  final modified = result["modified"]!.toList();
  final unchanged = result["unchanged"]!.toList();

  return MapChanges(
    added: added,
    removed: removed,
    modified: modified,
    unchanged: unchanged,
  );
}