Dart Collection Library
Working with Lists, Sets, and Maps in Dart
📚 What are Dart Collections?
Dart collections are built-in data structures like Lists, Sets, and Maps that help you store and organize multiple values efficiently in your programs.
// Simple List example
List<String> fruits = ['apple', 'banana', 'orange'];
print(fruits[0]); // Output: apple
Output:
apple
Core Collection Types
Lists
Ordered collection of items
List<int> numbers = [1, 2, 3];
numbers.add(4);
Sets
Unique items collection
Set<String> colors = {'red', 'blue'};
colors.add('green');
Maps
Key-value pairs collection
Map<String, int> ages = {
'John': 25,
'Jane': 30
};
Iterables
Base for all collections
for (var item in list) {
print(item);
}
🔹 Working with Lists
Lists are the most common collection type in Dart:
// Creating and manipulating lists
List<String> animals = ['cat', 'dog', 'bird'];
// Adding items
animals.add('fish');
animals.addAll(['rabbit', 'hamster']);
// Accessing items
print(animals[0]); // First item
print(animals.length); // Number of items
// Removing items
animals.remove('cat');
animals.removeAt(0);
print(animals); // [bird, fish, rabbit, hamster]
Output:
cat
6
[bird, fish, rabbit, hamster]
🔹 Working with Sets
Sets store unique values and are great for removing duplicates:
// Creating sets
Set<int> uniqueNumbers = {1, 2, 3, 2, 1}; // Duplicates removed
print(uniqueNumbers); // {1, 2, 3}
// Adding and checking items
uniqueNumbers.add(4);
print(uniqueNumbers.contains(2)); // true
// Set operations
Set<int> otherSet = {3, 4, 5};
print(uniqueNumbers.union(otherSet)); // {1, 2, 3, 4, 5}
print(uniqueNumbers.intersection(otherSet)); // {3, 4}
Output:
{1, 2, 3}
true
{1, 2, 3, 4, 5}
{3, 4}
🔹 Working with Maps
Maps store key-value pairs for quick lookups:
// Creating and using maps
Map<String, String> capitals = {
'USA': 'Washington DC',
'France': 'Paris',
'Japan': 'Tokyo'
};
// Accessing values
print(capitals['USA']); // Washington DC
// Adding new entries
capitals['Germany'] = 'Berlin';
// Iterating through maps
capitals.forEach((country, capital) {
print('$country: $capital');
});
// Getting keys and values
print(capitals.keys.toList()); // [USA, France, Japan, Germany]
Output:
Washington DC
USA: Washington DC
France: Paris
Japan: Tokyo
Germany: Berlin
[USA, France, Japan, Germany]