{

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. 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.

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);
}
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: Find a Given String is numeric or not

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