Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare Lists for equality in Dart?

Tags:

dart

I'm comparing two lists in Dart like this:

main() {     if ([1,2,3] == [1,2,3]) {         print("Equal");     } else {         print("Not equal");     }    } 

But they are never equal. There doesn't seem to be an equal() method in the Dart API to compare Lists or Collections. Is there a proper way to do this?

like image 566
Mark B Avatar asked May 01 '12 21:05

Mark B


People also ask

How do you know if two lists are equal in darts?

Check if two Lists are Equal Element Wiselist1 and list2 are equal. list1 and list3 are not equal.

How do you compare lists in flutter?

here == operator the instance of the list not the content, where are equals method compare the data inside lists. List<String>list3=list1; print(list1==list3);

How do you compare two lists the same?

For the two lists to be equal, each element of the first list should be equal to the second list's corresponding element. If the two lists have the same elements, but the sequence is not the same, they will not be considered equal or identical lists.

How do you compare in darts?

Dart – Compare Stringsnegative value if first string is less than the second string. zero if first string equals second string. positive value if first string is greater than the second string.


1 Answers

To complete Gunter's answer: the recommended way to compare lists for equality (rather than identity) is by using the Equality classes from the following package

import 'package:collection/collection.dart'; 

Edit: prior to 1.13, it was import 'package:collection/equality.dart';

E.g.:

Function eq = const ListEquality().equals; print(eq([1,'two',3], [1,'two',3])); // => true 

The above prints true because the corresponding list elements that are identical(). If you want to (deeply) compare lists that might contain other collections then instead use:

Function deepEq = const DeepCollectionEquality().equals; List list1 = [1, ['a',[]], 3]; List list2 = [1, ['a',[]], 3]; print(    eq(list1, list2)); // => false print(deepEq(list1, list2)); // => true 

There are other Equality classes that can be combined in many ways, including equality for Maps. You can even perform an unordered (deep) comparison of collections:

Function unOrdDeepEq = const DeepCollectionEquality.unordered().equals; List list3 = [3, [[],'a'], 1]; print(unOrdDeepEq(list2, list3)); // => true 

For details see the package API documentation. As usual, to use such a package you must list it in your pubspec.yaml:

dependencies:   collection: any 
like image 120
Patrice Chalin Avatar answered Sep 21 '22 14:09

Patrice Chalin