What are Collection Methods?
Dart provides a rich set of methods to work with collections like List, Set, and Map. These methods allow you to iterate, transform, filter, combine, and reduce collections in a functional and expressive way. Most of these methods come from the Iterable class, which List and Set implement, and from the Map class itself. Mastering these methods will make your code more concise, readable, and less error‑prone.
- Iteration Methods
forEach()
Executes a function on each element of the collection. It does not return a value (just performs side effects).
- Transformation Methods
map()
Transforms each element into a new value. Returns a new lazy Iterable; call toList() or toSet() to materialise.
expand()
Transforms each element into zero or more elements. Returns a flattened iterable.
- Filtering Methods
where()
Returns a new lazy iterable containing only elements that satisfy the given predicate.
firstWhere(), lastWhere(), singleWhere()
Find the first, last, or only element matching a condition. Provide an optional orElse function if no element is found.
- Checking Conditions
any() and every()
any returns true if at least one element satisfies the condition. every returns true if all elements satisfy the condition.
contains()
Checks if the collection contains a specific element (uses == equality).
- Reduction Methods
reduce()
Combines all elements using a given function. The collection must not be empty. The result type is the same as the element type.
fold()
Similar to reduce, but takes an initial value and can return a different type. Safe for empty collections.
- Sorting and Ordering
sort() (List only)
Sorts the list in place. You can provide a custom comparison function.
reversed (List only)
Returns an iterable of the elements in reverse order. To get a list, call toList().
shuffle() (List only)
Randomly shuffles the list in place.
- Taking and Skipping
take(), skip()
takeWhile(), skipWhile()
- Converting Between Collections
- Map‑Specific Methods
keys, values, entries
putIfAbsent()
update() and updateAll()
removeWhere()
- Set‑Specific Methods
union(), intersection(), difference()
retainAll() and removeAll()
Chaining Methods
Many collection methods return iterables, so you can chain them to perform complex transformations in a readable way.
Complete Example
Key Takeaways
forEachperforms an action on each element.
maptransforms each element into something new.
wherefilters elements based on a condition.
anyandeverytest conditions across the collection.
reduceandfoldcombine elements into a single value.
- Lists have additional methods like
sort,shuffle, andreversed.
- Lists have additional methods like
- Maps have
keys,values,entries,putIfAbsent,update, andremoveWhere.
- Maps have
- Sets support mathematical operations:
union,intersection,difference.
- Sets support mathematical operations:
- Methods can be chained to create powerful data processing pipelines.