2 ways to remove duplicate items from a list in Dart

Last updated on January 16, 2022 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 convert each item of the list to a JSON string then use toSet() and toList() as 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}]

Conclusion

You’ve learned how to remove duplicates from a list in Dart. This knowledge is really helpful when developing programs that require some sort of uniqueness. If you’d like to explore more new and interesting stuff in Dart and Flutter then take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles