There are times when you need to provide a function, but you may not need to use that function in other areas of your code. In such a case, you can provide an anonymous function instead.
This is a function that has no name.
Meaning, you provide a function header and function body, but you leave out the name since you won’t be using it again.
In flutter, you might use an anonymous function for callbacks. For example, when the user taps a button, you’ll want to fire off some code. Instead of writing a function and passing in that function, you’ll write that function inline.
Lets put anonymous function to works.
To get started, open up dartpad in a browser. We’re going to create a function to process a list scores, passing in a function. We’ve done this previous episode, but we’ll use an anonymous function.
First, let’s create our modify scores buttons. This will take in a list of scores and a function to process each element in the list. We’ve written this in a previous episode so it should be familiar to you.
int modifyScores(List<int> scores, int Function(int, int) processor) {
var total = 0;
for (var score in scores) {
total += processor(score, 2);
}
return total;
}
Now in the main function, we’ll get started by creating a list of scores.
var scores = [56, 85, 34];
Next, we’ll call our function, storing it in a variable.
var total = modifyScores(scores,
At this point, we’ll create an anonymous function. Remember, it doesn’t take a name. You just write the function. Try it out. See if you can do it. Don’t worry - I’ll wait.
Okay let’s do this now. First, I’ll add my parameters followed by braces.
(int a, int b) {
});
Next, I’ll return the result of multiplying both numbers.
return a * b;
And look at that - we’ve defined a function with no name. Let’s print out the total.
print(total);
Now run the program. We get a result using our anonymous function. Now using arrow notation, we can condense it even further.
var total = modifyScores(scores, (int a, int b) => a * b );
The arrow notation makes the function much easier to read without the braces.