Collection Methods in Dart
In this lesson, you will learn about Collection Methods in Dart. These methods allow you to filter, transform, search, and process data efficiently from Lists, Sets, and Maps.
Collection methods are heavily used in real-world applications such as data analytics, API responses, dashboards, reports, and business logic.
Why Collection Methods Matter
Without collection methods, you would need long loops and complex logic. With them, you can write:
- Cleaner code
- Shorter logic
- More readable programs
- Fewer bugs
Sample Dataset
We will use this list of monthly sales figures (in USD) for examples.
List monthlySales = [1200, 950, 1800, 2100, 400, 1600];
1. forEach()
The forEach() method is used to iterate through each element.
monthlySales.forEach((sale) {
print("Sale amount: $sale");
});
Best for logging, printing, or simple operations.
2. map()
The map() method transforms each element and returns a new list.
Example: Add 10% bonus to each sale.
var updatedSales = monthlySales.map((sale) {
return sale + (sale * 0.10).toInt();
}).toList();
print(updatedSales);
3. where()
The where() method filters elements based on a condition.
Example: Get sales above 1500.
var highSales = monthlySales.where((sale) => sale > 1500).toList();
print(highSales);
4. reduce()
The reduce() method combines all elements into a single value.
Example: Calculate total sales.
int totalSales = monthlySales.reduce((a, b) => a + b);
print("Total Sales: $totalSales");
5. fold()
The fold() method works like reduce, but allows an initial value.
Example: Start total from 1000 (opening balance).
int grandTotal = monthlySales.fold(1000, (sum, sale) => sum + sale);
print(grandTotal);
6. any()
Checks if at least one element satisfies a condition.
Example: Did any month cross 2000?
bool hasHighSale = monthlySales.any((sale) => sale > 2000);
print(hasHighSale);
7. every()
Checks if all elements satisfy a condition.
Example: Are all sales above 500?
bool allAbove500 = monthlySales.every((sale) => sale > 500);
print(allAbove500);
8. firstWhere()
Finds the first element that matches a condition.
Example: First sale above 1500.
int firstHighSale = monthlySales.firstWhere((sale) => sale > 1500);
print(firstHighSale);
9. sort()
Sorts the collection in ascending order.
monthlySales.sort();
print(monthlySales);
For descending order:
monthlySales.sort((a, b) => b.compareTo(a));
print(monthlySales);
10. Map Collection Methods
Collection methods also work with maps.
Example: Employee salaries.
Map salaries = {
"Alice": 50000,
"Bob": 62000,
"Charlie": 48000
};
Filter high earners:
var highEarners = salaries.entries
.where((e) => e.value > 50000)
.map((e) => e.key)
.toList();
print(highEarners);
Real-World Use Cases
- Filtering API responses
- Calculating totals and averages
- Sorting dashboards
- Validating data
- Transforming user inputs
📝 Practice Exercises
Exercise 1
From a list of numbers, filter values greater than 100.
Exercise 2
Convert a list of prices into prices with 18% tax.
Exercise 3
Check if any number in a list is negative.
✅ Practice Answers
Answer 1
List nums = [40, 120, 80, 200];
var result = nums.where((n) => n > 100).toList();
print(result);
Answer 2
List prices = [100, 200, 300];
var withTax = prices.map((p) => p + (p * 0.18).toInt()).toList();
print(withTax);
Answer 3
List values = [5, 10, -3];
print(values.any((v) => v < 0));
What’s Next?
In the next lesson, you will learn about Strings in Dart and how to manipulate, format, and process text efficiently.