If you’re interested in Dart/Flutter programming, here’s a little example of how to pass a Dart function into another function or method. The solution is basically a three-step process.
Step 1: Define a Dart method that takes a function parameter
First, define a Dart method that takes a function as a parameter, such as this exec
method:
// 1 - define a method that takes a function
void exec(int i, Function f) {
print(f(i));
}
That example take an int
parameter as well as a Dart Function
parameter. Then it applies the function f
to the integer i
, and prints the result.
Step 2: Create one or more functions to pass into that function parameter
Next, create one or more functions that you can pass into the exec
method:
// 2 - define a function to pass in
int plusOne(int i) => i + 1;
int double(int i) => i * i;
Step 3: Pass the functions into the method
Finally, pass those functions into the exec
method:
// 3 - pass the functions into the method
exec(10, plusOne);
exec(10, double);
The output of that code is:
11
100
You can also pass lambda expressions into function parameters
Note that in addition to passing functions into functions, you can also pass lambda expressions into methods that have function parameters. These two examples also print out 11
and 100
:
// 4 - note that you can also pass in lambda expressions
exec(10, (x) => x + 1); //plusOne
exec(10, (x) => x * x); //double
Summary
In summary, if you wanted to see how to write a Dart method that takes a function parameter, I hope these examples are helpful.