Programming in Dart: Functions & Closures

Jun 21 2022 · Dart 2.16, Flutter, DartPad

Part 2: Learn Anonymous Functions & Closures

14. Create a Closure

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: 13. Challenge: Write an Anonymous Method Next episode: 15. Understand Generics

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: 14. Create a Closure

Dart contains a cool feature that you can find in other languages - that is, you put a function inside of another function?

Now why would you want to do this? Well, let’s say you were writing a filtering function. Yet the source data is encoded, so you need another function to decode the data. Now that function isn’t used anywhere else in your program so it makes sense to nest it in that function.

Now sometimes, your functions will return another function. This gets interesting when we return our nested function. This returned nested function is called a closure because the returned function encapsulates -

or closes over - all the variables in the parent function. This means, the function has state.

Yes, that sound weird, but its a great way to keep track of internal state and like variables, can be passed around the function. Let’s play around with some closures.

To get started, open DartPad.dev. We’re going to create a function called apply multiplier. We will pass in a multiplier to the that we can use to multiply other numbers.

First let’s define the function taking in a multiplier.

Function applyMultiplier(num multiplier) {

}

This multiplier number is passed into the body of the function. Now let’s have it return a closer.

return (num value) {
    return value * multiplier;
};

Our closure takes in a value which is multiplies by our multiplier. You see, the closure captures the multiplier value. Now lets create a series of different closures.

var doubleMultiplier = applyMultiplier(2);
var tripleMultiplier = applyMultiplier(3);
var quadMultiplier = applyMultiplier(4);

Now lets call our multiplies on the number ten.

print(doubleMultiplier(10));
print(tripleMultiplier(10));
print(quadMultiplier(10));

Now run the program. We get all our modifiers. Notice that each closure maintains its own state. This is just scratching the surface of object oriented programing which is covered in the next course. But before you do anything with objects, you first need to have an understanding of generics which is coming up next.