Introduction
In this article, we will be learning about the anonymous function in dart. We have learned about the functions in the dart. If you haven't, go to this link. We have seen that we can give names to almost all functions, but apart from the named function, some functions are unnamed, and these functions are called anonymous functions, lambda or closure.
An anonymous function works the same as the name function and takes the comma-separated parameters with optional type annotations. You are free to assign an anonymous function to a variable so that you can add or remove it from a collection.
Syntax:
(parameters)
{
//code block
}
Examples of Dart’s Anonymous Function
Example: In this example, we will show the use of the forEach anonymous function.
Code:
void main() {
const shows= ['Friends', 'Game of Thrones', 'Peaky Blinders','Money Heist'];
print("Some Popular Shows");
//Using forEach anonymous function
shows.forEach((item) {
print('${shows.indexOf(item)}: $item');
});
}
Output:
Some Popular Shows
0: Friends
1: Game of Thrones
2: Peaky Blinders
3: Money Heist
Explanation: The forEach function will iterate over the list and print all the names from the list.
Example: In this example, we modify the code of the above example.
Code:
void main() {
const shows = ['Friends', 'Game of Thrones', 'Peaky Blinders','Money Heist'];
print("Some Popular Shows");
//If there is only one return statements we can use => instead of using curly braces
shows.forEach((item) => print('${shows.indexOf(item)}: $item'));
}
Output:
Some Popular Shows
0: Friends
1: Game of Thrones
2: Peaky Blinders
3: Money Heist
Explanation: Here, we modified the code of the above example, main aim is to show the alternate way of the single return statement. If the function has only one return statement in its body, we can also write like this.
Example: We show how to pass an anonymous function to any other function as a parameter in this example.
Code:
//This example has both named and anonymous function
//Try to observe the subtle difference.
void testFun(int x, int y, int z, Function oper){
//oper is of type Function and it perform the function which we have passed.
print("Integers are: $x, $y and $z");
//Storing the result into res.
int res = oper(x,y,z);
print("Result after applying operation: $res");
}
void main() {
int a = 40, b = 20, c = 30;
//testFun is a simple named function.
testFun(a,
b,
c,
//Here we are passing anonymous function as argument.
//It will return the result after applying this operation on these integers.
(int a, int b, int c){ return a+b-c; }
);
}
Output:
Integers are: 40, 20 and 30
Result after applying operation: 30
Explanation: Here, from the main function, we call testFun() and pass another function as its parameter. The last parameter we have provided is our anonymous function, which takes three parameters and returns a result value.





