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?
Check if two Lists are Equal Element Wiselist1 and list2 are equal. list1 and list3 are not equal.
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);
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.
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.
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 Map
s. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With