An anonymous function in Dart is like a named function but they do not have names associated with it. An anonymous function can have zero or more parameters with optional type annotations. An anonymous function consists of self-contained blocks of code and that can be passed around in our code as a function parameter.
- In Dart most of the functions are named functions we can also create nameless function knows as an anonymous function, lambda, or closure.
- In Dart, we can assign an anonymous function to constants or variables; later, we can access or retrieve the value of closure based on our requirements:
Syntax:
(parameter_list) {
statement(s)
}
Anonymous Function in forEach()
Example:
// Dartprogram to illustrate
// Anonymous functions in Dart
void main()
{
var list = ["Shubham","Nick","Adil","Puthal"];
print("GeeksforGeeks - Anonymous function in Dart");
list.forEach((item) {
print('${list.indexOf(item)} : $item');
});
}
Output:
GeeksforGeeks - Anonymous function in Dart
0 : Shubham
1 : Nick
2 : Adil
3 : Puthal
This example defines an anonymous function with an untyped parameter, item. The function, invoked for each item in the list, prints a string that includes the value at the specified index.
Assigning an Anonymous Function to a Variable
In Dart, functions are treated as first-class objects, allowing us to assign an anonymous function to a variable and use it like a regular function.
Example:
void main() {
// Assigning an anonymous function to a variable
var multiply = (int a, int b) {
return a * b;
};
print(multiply(5, 3)); // Output: 15
}
Output:
15Using an Anonymous Function as a Callback
Anonymous functions are widely used in asynchronous operations like button clicks or API calls.
Example:
void performOperation(int a, int b, Function operation) {
print('Result: ${operation(a, b)}');
}
void main() {
// Passing an anonymous function
performOperation(4, 2, (a, b) => a + b);
}
Output:
Result: 6