How do I check if two HashMaps are equal in Dart?

Viewed 39

The default behavior for all Objects in Dart is to return true if and only if this object and other are the same object. How do I check if the values are the same?

import 'dart:collection' show HashMap;

final Map<int, String> planets1 = HashMap(); // Is a HashMap
final Map<int, String> planets2 = HashMap(); // Is another HashMap
planets1.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
planets2.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
print(planets1 == planets2); // prints false
3 Answers

First import this package:

import 'package:collection/equality.dart';

and then print it out:

print(MapEquality().equals(planets1, planets1));

Try this

print(planets1.toString() === planets2.toString()); // prints true
import 'dart:collection';

import 'package:quiver/collection.dart';

void main() {
  final Map<int, String> planets1 = HashMap(); // Is a HashMap
  final Map<int, String> planets2 = HashMap(); // Is another HashMap
  planets1.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
  planets2.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
  print(mapsEqual(planets1, planets2)); // prints true
}

Related