To implement a closure in Dart, follow these steps:
- To add a closure to a function, you have to essentially define another function signature inside a function:
void callbackExample(void callback(String value)) {
callback('Hello Callback');
}
- Defining closures inline can get quite verbose. To simplify this, Dart uses the typedef keyword to create a custom type alias that will represent the closure. Let's create a typedef called NumberGetter, which will be a function that returns an integer:
typedef NumberGetter = int Function();
- The following function will take in a NumberGetter as its parameter and invoke it in its function:
int powerOfTwo(NumberGetter getter) {
return getter() * getter();
}
- Let's put this all together with a function that will use all these closure examples:
void consumeClosure() {
final getFour = () => 4;
final squared = powerOfTwo(getFour);
print(squared);
callbackExample((result) {
print(result);
});
}
- Finally, add an invocation to consumeClosure at the top of the playground method or in your main method:
consumeClosure();