In Dart, you can convert both lists to sets and compare them to check if they have the same elements regardless of order.
In this example,
list1
and list2
with the same set of elements.toSet()
method.==
operator.void main() {
List<int> list1 = [1, 2, 3];
List<int> list2 = [3, 2, 1];
bool result = list1.toSet() == list2.toSet();
print('Do the lists have the same elements? \$result');
}
Do the lists have the same elements? true
In this example,
list1
and list2
with different sets of elements.toSet()
method.==
operator.void main() {
List<int> list1 = [1, 2, 3];
List<int> list2 = [4, 5, 6];
bool result = list1.toSet() == list2.toSet();
print('Do the lists have the same elements? \$result');
}
Do the lists have the same elements? false
In this tutorial, we learned How to check if Two Lists have Same Elements (Regardless of Order) in Dart language with well detailed examples.