Dart| Flutter: Different ways to check differences between two lists with example

The list contains a growable collection of data. Sometimes you want to find the difference between the two lists.

For example, You have two declared lists

  List list1 = [1,5,10,20,25,30,35];
  List list2 = [1,5,7,25,29,30];

What is the difference between the above list? The difference is a common element that is repeated in both lists and is called a difference of the lists.

And the output

This example shows you multiple ways to find the difference between two lists.

Flutter/Dart find the difference in lists

There are multiple ways we can get the difference between multiple lists.

  • use the list removeWhere method

    List removewhere🔗 method removes an element that passes the function condition

  void removeWhere(bool Function(dynamic) condition)

In this example, From the first list, Removed the elements, whose elements are not present in the second list.

You can continue to apply the same logic if there are multiple lists. This mutates the original first list and the result contained in the first list.

Example code to find common elements in a list.

void main() {
  List list1 = [1, 5, 10, 20, 25, 30, 35];
  List list2 = [1, 5, 7, 25, 29, 30];
  list1.removeWhere((item) => !list2.contains(item));

  print(list1); //[1, 5, 25, 30]
}

Convert to Set and where the conditional pass

In this example, the First list is converted to a set to remove duplicates from the list Next, call the Where condition, which returns the Iterable of the list with conditional logic. Conditions logic is to check the existence of each element in a second set where the second list is converted. Finally, converted set to list using the toList() method.

Here is a difference between the two lists example

void main() {
  List list1 = [1, 5, 10, 20, 25, 30, 35];
  List list2 = [1, 5, 7, 25, 29, 30];
  List uniqueItemsList =
      list1.toSet().where((item) => list2.toSet().contains(item)).toList();

  print(uniqueItemsList); //[1, 5, 25, 30]
}

Conclusion

To summarize, Learned how to get different elements of multiple lists in the dart and flutter tutorial.