skip to Main Content

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


  1. 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:

    dependencies:
      collection: ^1.15.0
    

    Then, the following code should work:

    import 'package:collection/collection.dart';  // Import the collection package
    
    List<Map<String, Object>> orderList = [{"Nasi Goreng": 1}];
    
    ElevatedButton(
      onPressed: () {
        print(orderList);
    
        // Now we will use MapEquality to compare the map contents (not reference)
        final mapEquality = MapEquality();
        bool isEqual = mapEquality.equals(orderList[0], {"Nasi Goreng": 1});
        
        // Print whether the maps are equal
        print(isEqual);  // Now it should print true now
    
        // Assert based on map content equality, to be on the safe side
        assert(isEqual);
      },
      child: Text("+"),
    )
    
    Login or Signup to reply.
  2. 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}) );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search