Higher-order functions are a powerful feature in Dart that allow functions to be treated as first-class citizens. They can accept other functions as arguments or return functions as results, enabling more flexible and reusable code.
In Dart, higher-order functions are functions that can:
This concept is closely related to Dart Function Basics and Anonymous Functions.
One common use of higher-order functions is to accept other functions as parameters. This allows for more dynamic behavior and code reuse.
void performOperation(int a, int b, int Function(int, int) operation) {
print(operation(a, b));
}
void main() {
performOperation(5, 3, (a, b) => a + b); // Output: 8
performOperation(5, 3, (a, b) => a * b); // Output: 15
}
In this example, performOperation
is a higher-order function that accepts two integers and a function as arguments.
Higher-order functions can also return other functions, allowing for the creation of specialized functions on the fly.
Function multiplyBy(int factor) {
return (int number) => number * factor;
}
void main() {
var multiplyByTwo = multiplyBy(2);
var multiplyByThree = multiplyBy(3);
print(multiplyByTwo(5)); // Output: 10
print(multiplyByThree(5)); // Output: 15
}
Here, multiplyBy
returns a function that multiplies its input by a specified factor.
Higher-order functions are frequently used in:
They are particularly useful when working with Dart Lists and other Iterables.
By mastering higher-order functions, you'll be able to write more expressive and flexible Dart code, opening up new possibilities in your programming toolkit.