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:
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]
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"]
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"]
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"]
0 Comments