2 ways to remove duplicate items from a list in Dart

Last updated on December 3, 2020 A Goodman Loading... Post a comment

This article shows you 2 approaches to remove duplicate items from a list in Flutter. The first one works well for a list of primitive data types. The second one is a little bit more complex but works well with a list of maps or a list of objects.

Convert to Set then reverse to List

This is a simple and fast solution for a simple list.

Example:

void main(){
  final myNumbers = [1, 2, 3, 3, 4, 5, 1, 1];
  final uniqueNumbers = myNumbers.toSet().toList();
  print(uniqueNumbers);
  
  final myStrings = ['a', 'b', 'c', 'a', 'b', 'a'];
  final uniqueStrings = myStrings.toSet().toList();
  print(uniqueStrings); 
}

Output:

[1, 2, 3, 4, 5]
[a, b, c]

Remove duplicates from a list of maps or objects

Our strategy is to converting each item of the list to a JSON string then use toSet() and toList() like the first method.

Example:

import "dart:convert";
void main(){
  final myList = [
    {
      'name': 'Andy',
      'age': 41
    },
    {
      'name': 'Bill',
      'age': 43
    },
    {
      'name': 'Andy',
      'age': 41
    }
  ];
  
  // convert each item to a string by using JSON encoding
  final jsonList = myList.map((item) => jsonEncode(item)).toList();
  
  // using toSet - toList strategy
  final uniqueJsonList = jsonList.toSet().toList();
  
  // convert each item back to the original form using JSON decoding
  final result = uniqueJsonList.map((item) => jsonDecode(item)).toList();
  
  print(result); 
}

Output:

[{name: Andy, age: 41}, {name: Bill, age: 43}]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles