How can I compare Lists for equality in Dart?

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

Leave a Comment