dart

Dart program to remove duplicate items from a list

If you are using dart or flutter to develop your application and want to remove the same items from the list then you can use one of these methods explained in this post.

List numbers = [10, 30, 40, 10, 30, 20, 10, 40];
  
List result = Set.of(numbers).toList();

print(result);

Output

[10, 30, 40, 20]

We are Using Set.of() and toList() functions to remove or filter duplicate values from a list in Flutter or Dart. In the above code snippet:

  1. We have defined a list named numbers that contains multiple duplicate items in it. We want to remove the duplicate items from it.
  2. We are using code Set.of(numbers).toList() to remove the duplicate items and assign the output to the result named variable.
  3. Printing the output as the result list variable.

Example 2: Using toSet() and toList() dart functions:

We can also remove the duplicates from the above list using the below code example.

List numbers = [10, 30, 40, 10, 30, 20, 10, 40];
  
List output = numbers.toSet().toList();
  
print(output);

Output

[10, 30, 40, 20]

Remove duplicates using the spread operator

We know that spread operators are very useful in multiple operations in dart programming. Here we will show a code example that uses spread operator ... to remove the duplicate values from the list.

Code Example

List names = ['John', 'Rick', 'Grimes', 'Rick', 'John', 'Carol'];
  
List output = [...{...names}];
  
print(output);

Output

["John", "Rick", "Grimes", "Carol"]

Use LinkedHashSet to remove the same items from a list

We can also use LinkedHashSet which is imported from the collection module of the dart. We will be using from() and toList() functions of the dart to do that.

import "dart:collection";

void main() {
  List names = ['John', 'Rick', 'Grimes', 'Rick', 'John', 'Carol'];
  
  List<String> result = LinkedHashSet<String>.from(names).toList();
  
  print(result);
}

Output

["Rick", "Carol", "Daryl", "Negan", "Carl"]

Use where() to get distinct records from the list

We can also filter out duplicate items from a list using the where() function where we can define a Set that will add the items that are already added and we will only add items to the output list that are already not added.

Code Example

List names = ['John', 'Rick', 'Grimes', 'Rick', 'John', 'Carol'];
  
final added = <String>{};
  
final result = names.where((item) => added.add(item)).toList();

print(result);

Output

["Rick", "Carol", "Daryl", "Negan", "Carl"]
Was this helpful?