I have two lists:
List fruits = ['apples', 'bananas'];
List foods = ['apples', 'bananas'];
How can I compare fruits and foods and ensure that both lists have the same objects in the same order?
dart has a listEquals method, does compare each element by element in the list, and returns equal comparison result with boolean type. true: Returns true if two lists are equal with ignoring the order of elements. false: Elements in the list.
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);
Java equals() method of List interface compares the specified object with the list for equality. It overrides the equals() method of Object class. This method accepts an object to be compared for equality with the list. It returns true if the specified object is equal to the list, else returns false.
The recommended way to compare lists for equality (rather than identity) is by using the Equality classes from the following package
import 'package:collection/equality.dart';
E.g.,
Function eq = const ListEquality().equals;
print(eq(fruits, foods)); // => true
This works for your case because the fruits
and foods
contain corresponding arguments 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 deepEq = const DeepCollectionEquality.unordered().equals;
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