I’m trying to compare values from a List which consists of Map<String, Object>, but the result always returns false despite the value I’m comparing it with is the same. Is there something I did wrong here?
List<Map<String, Object>> orderList = [{"Nasi Goreng": 1}];
...
ElevatedButton(onPressed: () {
print(orderList);
assert(orderList[0] == {"Nasi Goreng": 1});
}, child: Text("+"))
I tried using assert
, contains
and indexOf
, but all those returned false, false and -1. I expected one of those should at least return true or returns the index of the item (which is 0), but I keep getting false. What I get from running assert is:
Failed assertion: line 178 pos 68: 'orderList[0] == {"Nasi Goreng": 1}': is not true.
2
Answers
When you use comparison in Dart, the ‘==’ condition means that the references of the objects are identical, not their value.
There is, however, a class named ‘collection’. So, first, add it:
Then, the following code should work:
When you try to compare Maps in Dart by using
==
, Dart will basically compare eachhashCode
of those Maps. Since these Maps are two different Object, the hashCode of each Map is distinct, and==
comparison will always returnfalse
:To compare equality of
Map
s, you can usemapEquals
from ‘package:flutter/foundation.dart’(As one of solutions of similar question produced in how to check two maps are equal in dart)
Example: