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]


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

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example