What are Higher-Order Functions?
A higher‑order function is a function that takes one or more functions as arguments, returns a function, or both. In Dart, functions are first‑class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions. Higher‑order functions are a cornerstone of functional programming and enable powerful, expressive code patterns.
Built‑in Higher‑Order Functions in Dart
Dart's collection classes come with many higher‑order functions. The most common ones are:
forEach– performs an action on each element.
map– transforms each element into a new value (returns a lazy iterable).
where– filters elements based on a condition.
reduce– combines all elements into a single value.
fold– similar to reduce but with an initial value.
any/every– test a condition on elements.
firstWhere/lastWhere– find elements.
Writing Your Own Higher‑Order Function
You can define your own functions that accept other functions. This is useful for creating reusable algorithms where the specific behavior can be supplied by the caller.
The parameter action is a function that takes an int and returns void. You can pass any matching function, including lambdas.
Returning Functions (Function Factories)
A higher‑order function can also return a function. This is useful for creating function factories or closures with pre‑configured behavior.
Here, makeMultiplier returns a lambda that captures factor – a classic example of a closure.
Type Aliases for Function Types
To improve readability, you can define a typedef for a function type. This makes your code more self‑documenting.
Practical Example: Custom Filter Function
Key Takeaways
- Higher‑order functions accept or return other functions, enabling flexible and reusable code.
- Dart provides many built‑in higher‑order functions for collections (
map,where,reduce, etc.).
- Dart provides many built‑in higher‑order functions for collections (
- You can create your own higher‑order functions to encapsulate algorithms.
- Returning functions (function factories) allows you to generate customized behavior.
- Use
typedefto give meaningful names to function types.
- Use