This article shows you a couple of different ways to remove duplicate items from a list in Dart (and Flutter, of course). 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 and 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:
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- How to Flatten a Nested List in Dart
- Inheritance in Dart: A Quick Example
- Dart: Get Host, Path, and Query Params from a URL
- Flutter & Dart: Ways to Generate Random Strings
- Flutter: ListView Pagination (Load More) example
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.