Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two lists as being equal and containing the same objects, in Dart?

Tags:

dart

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?

like image 349
Seth Ladd Avatar asked Oct 31 '13 18:10

Seth Ladd


People also ask

How do you compare two lists in darts?

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.

How do you compare two lists of objects 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 of objects?

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.


1 Answers

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 Maps. 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
like image 110
Patrice Chalin Avatar answered Nov 15 '22 17:11

Patrice Chalin