Programming in Dart: Functions & Closures

Jun 21 2022 · Dart 2.16, Flutter, DartPad

Part 2: Learn Anonymous Functions & Closures

11. Use Anonymous Functions

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Introduction Next episode: 12. Map & Filter Collections

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 11. Use Anonymous Functions

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.