How can I compare List and Maps in Flutter

Published October 27, 2021


There are two ways to compare two lists in flutter equals and DeepCollectionEquality collection method. Similarly we can also compare two maps in flutter

 

Let say we have two list which contains the data below

List<String>list1=["Sunday","Monday","Tuesday","Wednesday"];
List<String>list2=["Sunday","Monday","Tuesday","Wednesday"];

 

Now compare these two lists by using equals(==) operator

 

now print compare these two list by

print(list1==list2);
print(list1.equals(list2));

 

here the output will be like below

false

true

 

here == operator the instance of the list not the content, where are equals method compare the data inside lists.

that's why the results came like above

 

let's create one more list by assigning list1

List<String>list3=list1;

print(list1==list3);

 

now this will print true.

 

Here the list is just strings, if suppose we have the list with custom objects, then how we will compare two lists.

 

List<Day>list1=[Day(1,"Sunday"),Day(2,"Monday"),Day(3,"Tuesday")];
List<Day>list2=[Day(1,"Sunday"),Day(2,"Monday"),Day(3,"Tuesday")];
print(list1==list2);

 

when we run it will throw error like

type 'List<String>' is not a subtype of type 'List<Day>' of 'function result'

 

Then how we will compare these custom object list in flutter, there the DeepCollectionEquality come to the picture.

To compare custom object lists we will use DeepCollectionEquality

 

First create instance of DeepCollectionEquality

then apply equals() method by passing the lists

DeepCollectionEquality dc=DeepCollectionEquality();
print("Compare custom list ${dc.equals(list1,list2)}");

 

This will print out put like

true

 

Then what is DeepCollectionEquality

DeepCollectionEquality is a collection class Creates a deep equality on collections where the order of lists and iterables are not considered important. That is, lists and iterables are treated as unordered iterables

 

Compare Two maps using DeepCollectionEquality.

Let's take two maps

Map<String, dynamic> student1 = {
  'name': 'DartStdent',
  'class': '10th',
  'marks': 98,
  'address': {
    'Hno': '2-1',
    'state': 'Telangana',
    'Country': 'India',
  }
};

Map<String, dynamic> student2 = {
  'name': 'DartStdent',
  'class': '10th',
  'marks': 98,
  'address': {
    'Hno': '2-1',
    'state': 'Telangana',
    'Country': 'India',
  }
};

 

print("Compare two maps ${dc.equals(student1,student2)}");

 

Output:

Compare two maps true

 

Conclusion: In this flutter tutorial we covered compare lists and maps inside flutter using equals() method and DeepCollectionEquality  collection class


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

24 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions