Dart| Flutter: Different ways to check differences of 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 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 of lists

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

  • use 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 do 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 toList() method

Here is a difference of 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]


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

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.

Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example