{

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


Delete duplicate elements from list in dart or flutter

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);
}
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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart