map()
Transforms each element and returns a new iterable:
var numbers = [1, 2, 3, 4, 5];
var doubled = numbers.map((n) => n * 2).toList();
print(doubled); // [2, 4, 6, 8, 10]
var names = ['alice', 'bob', 'carol'];
var upper = names.map((n) => n.toUpperCase()).toList();
print(upper); // [ALICE, BOB, CAROL]
where()
Filters elements that match a condition:
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var evens = nums.where((n) => n % 2 == 0).toList();
print(evens); // [2, 4, 6, 8, 10]
var scores = [45, 72, 88, 91, 55, 60];
var passed = scores.where((s) => s >= 60).toList();
print(passed); // [72, 88, 91, 60]
reduce() & fold()
var nums = [1, 2, 3, 4, 5];
// reduce — combine elements (no initial value)
int sum = nums.reduce((a, b) => a + b);
print(sum); // 15
int product = nums.reduce((a, b) => a * b);
print(product); // 120
// fold — combine with an initial value
int sumFrom10 = nums.fold(10, (acc, n) => acc + n);
print(sumFrom10); // 25
// fold works on empty lists; reduce throws on empty
var empty = <int>[];
int result = empty.fold(0, (acc, n) => acc + n);
print(result); // 0
any() & every()
var ages = [15, 22, 30, 17, 45];
print(ages.any((a) => a >= 18)); // true (at least one adult)
print(ages.every((a) => a >= 18)); // false (not all adults)
print(ages.any((a) => a > 50)); // false
Full Example
void main() {
var students = [
{'name': 'Alice', 'score': 88},
{'name': 'Bob', 'score': 54},
{'name': 'Carol', 'score': 92},
{'name': 'Dave', 'score': 61},
];
var passed = students.where((s) => s['score'] as int >= 60).toList();
var names = passed.map((s) => s['name']).toList();
var avg = students.fold<int>(0, (sum, s) => sum + (s['score'] as int))
/ students.length;
print('Passed: $names');
print('Average: $${avg.toStringAsFixed(1)}');
print('All passed: $${students.every((s) => (s['score'] as int) >= 60)}');
}
Output:Passed: [Alice, Carol, Dave]
Average: 73.8
All passed: false
🧠 Quiz
1. What does where() return?
- A) A single value
- B) A filtered Iterable ✅
- C) A Map
- D) A bool
2. What is the difference between reduce() and fold()?
- A) No difference
- B) fold() takes an initial value and works on empty lists ✅
- C) reduce() is faster
- D) fold() only works on numbers
Summary
Dart collections support functional operations: map() transforms, where() filters, reduce() combines, fold() combines with initial value, any() checks at least one match, every() checks all match. Chain them for powerful data processing pipelines.