{

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


List contains multiple values, sometimes you need to delete the duplicate from the list. Delete duplicate elements from list in dart or flutter

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.

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 an code to delete duplicates

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

  print(numbers);
  print(result);
}
THE BEST NEWSLETTER ANYWHERE
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
Subscribe
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