How to delete duplicates in a Dart List? Flutter List| Dart By Example

The list contains multiple values, sometimes you need to delete the duplicate from the list.

In this post, We are going to learn how to delete duplicates from List in Dart or flutter.

Dart list allows duplicate values, if you store the same value multiple values, It stores the value as a different element.

How to delete duplicate items from a list in Dart or Flutter?

There are multiple ways we can do

  • use toSet() method

Dart List contains toSet() method to convert to Set. Set does not allow duplicate values, so returns Set which contains unique elements. Convert set to List using toList() method.

The below example is to remove duplicate numbers from a list of numbers

void main() {
  var numbers = [12, 22, 22, 12, 61, 16, 16];
  var result = numbers.toSet().toList();

  print(numbers);
  print(result);
}

Another example is to delete duplicate strings from a list of strings

void main() {
  var numbers = ["one","two","one"];
  var result = numbers.toSet().toList();

  print(numbers);
  print(result);
}

Output:

[one, two, one]
[one, two]
  • use spread Operator Spread operators (three dots - …) are used to add the elements to collections.

    Here is a code to delete duplicates

  void main() {
  var numbers = ["one", "two", "one"];
  var result = [
    ...{...numbers}
  ];

  print(numbers);
  print(result);
}