Skip to content

fix: improve mapEquals to correctly compare maps with different key…#207

Merged
felangel merged 1 commit into
felangel:masterfrom
Danilospano00:master
Jan 4, 2026
Merged

fix: improve mapEquals to correctly compare maps with different key…#207
felangel merged 1 commit into
felangel:masterfrom
Danilospano00:master

Conversation

@Danilospano00

Copy link
Copy Markdown
Contributor

Status

READY

Breaking Changes

NO

Description

The actual version has a bug in mapEquals() that causes false positives when comparing maps with:

  • Same length
  • Different keys
  • At least one null value

🔴 The Bug Explained

Buggy Code

bool mapEquals(Map<Object?, Object?> a, Map<Object?, Object?> b) {
  if (identical(a, b)) return true;
  if (a.length != b.length) return false;
  for (final key in a.keys) {
    if (!objectsEquals(a[key], b[key])) return false;  // ❌ BUG HERE
  }
  return true;
}

The Problem

When you access b[key] and the key doesn't exist in map b, Dart returns null:

final map1 = {'a': 1, 'b': null};
final map2 = {'a': 1, 'c': null};  // 'b' doesn't exist

// Without containsKey:
map1['b']  // = null (explicit)
map2['b']  // = null (missing key!)
objectsEquals(null, null)  // = true ✅
// Result: mapEquals returns TRUE ❌ BUG!

Example with the BUG: User Permissions

class User extends Equatable {
  final Map<String, bool> permissions;
  
  @override
  List<Object> get props => [permissions];
}

final admin = User(permissions: {'read': true, 'write': null});
final guest = User(permissions: {'read': true, 'admin': null});

admin == guest;  // Returns TRUE 
// Admin and guest are treated as equal!

✅ Fix

added !b.containsKey(key)

bool mapEquals(Map<Object?, Object?> a, Map<Object?, Object?> b) {
  if (identical(a, b)) return true;
  if (a.length != b.length) return false;
  for (final key in a.keys) {
    if (!b.containsKey(key) || !objectsEquals(a[key], b[key])) return false;
  }
  return true;
}

…s and null values, add corresponding tests, and document the bug fix.
@felangel felangel added the bug Something isn't working label Jan 4, 2026
@felangel

felangel commented Jan 4, 2026

Copy link
Copy Markdown
Owner

Thanks for the fix! I'll get this merged and released shortly and apologies for the delay!

@felangel felangel left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM thanks so much for the fix!

@felangel felangel merged commit 622a3f8 into felangel:master Jan 4, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants