In Dart, Each function has a name, Example function is main(), also called named functions.
How do you create a function without a name?
In Dart, you create functions without a name, also called anonymous functions.
Anonymous functions contain zero or more arguments separated by a comma and also have type annotations
anonymous functions also called lambda or closures in Dart.
These functions can be assigned to variables or passed as an argument to functions.
Let’s see the normal function defined below
String function getMessage(String message){
return message;
}
The function can be called using with below syntax
getMessage("hello");
let’s see how the anonymous function
Dart closure or anonymous function example
Closure is a special function also called lambda expression
Here is an example
(arguments)=>{
return statement;
}
Arguments can be multiple arguments separated by a comma.
You can assign the closure functions to variables Let’s see the anonymous function declaration Here is an example of nameless functions
void main() {
// assign lambda function to a variable
var add = (int first, int second) => first + second;
print(add(10, 20));
// closure function without arrow syntax
var add1 = (int first, int second) {
return first + second;
};
print(add1(10, 20));
// closure function without assigning a variable
(int first, int second) {
print(first + second);
}(10, 20);
}
How to pass closure function as a parameter in A function
printData function accepts two arguments, first int type, the second is Closure Function of type Function.
Here is an example program
void printData(int price, double Function(int amount) calculateFn) {
var result = calculateFn(price);
print(result);
}
void main() {
var divideBy2 = (int price) {
return price / 2; // return a double type.
};
var divideBy5 = (int price) {
return price / 5; // return a double type.
};
const price = 50;
printData(price, divideBy2); // 100.0
printData(price, divideBy5); // 50.0
}
Dart closure or anonymous features
- It has no function name
- Arrow syntax used to create a closure
- Can assign to variables or pass as an argument
- If the body contains one expression, Return is an optional