Dart, the core language behind Flutter, provides powerful collection types that simplify data manipulation and storage. The most commonly used collection types in Dart are Lists, Sets, and Maps. Each collection serves a specific purpose, and understanding how they differ is essential for efficient programming in Dart.

1. Lists: Ordered Collection of Items
A List in Dart is an ordered group of objects. You can access items by their index, and they allow duplicate values. Dart lists are similar to arrays in other languages, but more flexible. Dart supports both fixed-length and growable lists.
Example:
List<String> fruits = ['Apple', 'Banana', 'Orange']; print(fruits[0]); // Output: Apple
Lists are best when the order of items matters, and you may have duplicates. For instance, shopping carts or recent activity logs.
2. Sets: Unordered and Unique
A Set is an unordered collection of unique items. If you add a duplicate value, it will automatically be ignored. This makes Sets ideal for filtering duplicate entries.
Example:
Set<int> numbers = {1, 2, 3, 3}; print(numbers); // Output: {1, 2, 3}
Sets are best when you need to ensure all elements are unique, such as storing user roles or tags.
3. Maps: Key-Value Pairs
A Map stores items in key-value pairs. Each key must be unique, and you can retrieve values using these keys. Dart Maps are particularly useful for structured data like configurations or user profiles.
Example:
Map<String, String> user = { 'name': 'Alice', 'email': 'alice@example.com' }; print(user['name']); // Output: Alice
Use Maps when you need fast lookup and association between data points.
Comparison Table: Dart Collection Types
Feature | List | Set | Map |
---|---|---|---|
Order | Yes | No | No (but preserves insertion order) |
Duplicates | Allowed | Not allowed | Keys not allowed to duplicate |
Access by Index | Yes | No | No |
Access by Key | No | No | Yes |
Best Practices:
- Use Lists when order matters and duplicates are acceptable.
- Use Sets when uniqueness is important and order doesn’t matter.
- Use Maps when working with key-value pairs or structured data.
Dart also supports collection if and spread operators, which help in building more dynamic and concise collections. For example:
var includeBanana = true; var items = ['Apple', if (includeBanana) 'Banana', 'Cherry'];
This flexibility makes Dart a powerful language for handling structured and dynamic data.
Explore More
For a broader understanding of Dart collections and additional features like Queue
, LinkedHashMap
, and HashSet
, refer to the official Dart documentation: Dart Collections Overview.