Dart Collections
Working with data structures in Dart
📦 Dart Collections Overview
Dart collections are data structures that store multiple values. The main types are Lists, Sets, and Maps, each serving different purposes for organizing and accessing data efficiently.
// Basic collections in Dart
List<String> fruits = ['apple', 'banana', 'orange'];
Set<int> numbers = {1, 2, 3, 4, 5};
Map<String, int> ages = {'Alice': 25, 'Bob': 30};
Types of Collections
Lists
Ordered collection with duplicates
List<String> colors = ['red', 'blue', 'red'];
Sets
Unique elements, no duplicates
Set<int> uniqueNumbers = {1, 2, 3, 2}; // {1, 2, 3}
Maps
Key-value pairs for data lookup
Map<String, int> scores = {'Alice': 95, 'Bob': 87};
Iterables
Base for all collection types
Iterable<int> numbers = [1, 2, 3, 4, 5];
🔹 Creating Collections
Different ways to create and initialize collections:
void main() {
// Lists - ordered, allow duplicates
List<String> fruits = ['apple', 'banana', 'apple'];
var numbers = [1, 2, 3, 4, 5];
// Sets - unique elements only
Set<String> uniqueFruits = {'apple', 'banana', 'orange'};
var uniqueNumbers = {1, 2, 3, 2}; // Duplicate 2 is ignored
// Maps - key-value pairs
Map<String, int> studentGrades = {'Alice': 95, 'Bob': 87};
var capitals = {'USA': 'Washington', 'France': 'Paris'};
print('Fruits: $fruits');
print('Unique numbers: $uniqueNumbers');
print('Grades: $studentGrades');
}
Output:
Fruits: [apple, banana, apple]
Unique numbers: {1, 2, 3}
Grades: {Alice: 95, Bob: 87}
🔹 Common Collection Operations
Basic operations you can perform on collections:
void main() {
List<int> numbers = [1, 2, 3];
// Adding elements
numbers.add(4);
numbers.addAll([5, 6]);
// Accessing elements
print('First: ${numbers.first}');
print('Last: ${numbers.last}');
print('Length: ${numbers.length}');
// Checking contents
print('Contains 3: ${numbers.contains(3)}');
print('Is empty: ${numbers.isEmpty}');
// Removing elements
numbers.remove(6);
print('After removing 6: $numbers');
}
Output:
First: 1
Last: 6
Length: 6
Contains 3: true
Is empty: false
After removing 6: [1, 2, 3, 4, 5]
🔹 Collection Methods
Useful methods for processing collections:
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Transform elements
var doubled = numbers.map((n) => n * 2).toList();
print('Doubled: $doubled');
// Filter elements
var evenNumbers = numbers.where((n) => n % 2 == 0).toList();
print('Even numbers: $evenNumbers');
// Reduce to single value
var sum = numbers.reduce((a, b) => a + b);
print('Sum: $sum');
// Check conditions
var hasEven = numbers.any((n) => n % 2 == 0);
var allPositive = numbers.every((n) => n > 0);
print('Has even: $hasEven, All positive: $allPositive');
}
Output:
Doubled: [2, 4, 6, 8, 10]
Even numbers: [2, 4]
Sum: 15
Has even: true, All positive: true