Dart – Check Equality for Lists
You can check if two lists are equal with respect to their elements.
Let us consider that two lists are equal if they have same elements throughout their length.
Check if two Lists are Equal Element Wise
In this example, we take three lists out of which two are equal with respect to their contents and the third list is different from the first two.
We shall write a function areListsEqual() to check if the given two lists are equal element by element. As a pre-requisite, we check if both the given variables are lists, and then compare their lengths.
Dart Program
</>
Copy
bool areListsEqual(var list1, var list2) {
// check if both are lists
if(!(list1 is List && list2 is List)
// check if both have same length
|| list1.length!=list2.length) {
return false;
}
// check if elements are equal
for(int i=0;i<list1.length;i++) {
if(list1[i]!=list2[i]) {
return false;
}
}
return true;
}
void main(){
List list1 = [24, 'Hello', 84];
List list2 = [24, 'Hello', 84];
List list3 = [11, 'Hi', 41];
if(areListsEqual(list1, list2)) {
print('list1 and list2 are equal in value.');
} else {
print('list1 and list2 are not equal in value.');
}
if(areListsEqual(list1, list3)) {
print('list1 and list3 are equal in value.');
} else {
print('list1 and list3 are not equal in value.');
}
}
Output
list1 and list2 are equal.
list1 and list3 are not equal.
Conclusion
In this Dart Tutorial, we learned how to check if two Lists are equal in their value.