Search code examples
flutterlistdartobject

Comparing the same result of List<Map<String, Object>> is not true


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.

Solution

  • When you try to compare Maps in Dart by using ==, Dart will basically compare each hashCode of those Maps. Since these Maps are two different Object, the hashCode of each Map is distinct, and == comparison will always return false:

    print(orderList[0].hashCode) // 329301310
    print({"Nasi Goreng": 1}.hashCode) // 743029473
    

    To compare equality of Maps, you can use mapEquals from 'package:flutter/foundation.dart' (As one of solutions of similar question produced in how to check two maps are equal in dart)

    Example:

    import 'package:flutter/foundation.dart';
    
    void main() {
      const orderedList = [{"Nasi Goreng": 1}];
      print( mapEquals(orderedList[0], {"Nasi Goreng": 1}) );
    }