skip to Main Content

For example, I have the following two dynamic maps that have the same keys and values:

 Map a = {
'name':'alex',
 'products': {'type':'cars'},
 'rate':100,
 'others':['not yet']
};

Map b = {
 'name':'alex',
 'products': {'type':'cars'},
 'rate':100,
 'others':['not yet']
};

when i call

print((a==b).toString()); => always print false why ?

How to check it in the correct way I need to know if these two maps have the same keys and values exactly.

2

Answers


  1. You can try DeepCollectionEquality class in here

    example:

    import 'package:collection/collection.dart';
    
    Map a = {
          'name': 'alex',
          'products': {'type': 'cars'},
          'rate': 100,
          'others': ['not yet']
        };
    
    Map b = {
          'name': 'alex',
          'products': {'type': 'cars'},
          'rate': 100,
          'others': ['not yet']
        };
    
    DeepCollectionEquality deepCollectionEquality =
            const DeepCollectionEquality();
    
    print(deepCollectionEquality.equals(a, b));
    
    Login or Signup to reply.
  2. You might need to do the following things(in the given order) in order to check whether two(or more) maps are equal or not

    1. should have same length(if lengths of all maps is null return true)
    2. iterate over the list of keys of any of the maps and check for the same key-value pairs in other maps, if "and" operation between them is false at any point then return false
    3. Return true in the end(this is returned only when all and operations in step 2 return true)

    Alternatively you can use the package https://api.flutter.dev/flutter/foundation/mapEquals.html.
    But the only drawback is that its takes only two maps as input

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search