Anonymous function in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

A function without a name is known as an anonymous function. They behave in the exact same manner as a normal named function would. The only difference between the named and an anonymous function is how different they are in syntax.

Anonymous functions are used in Dart to form closures. An anonymous function contains a self-contained block of codes, also it can be passed as a parameter to another function as well.

Anonymous function Syntax

(parameterList){
   // inner statement(s)
}

Example

Now, let's consider a simple example of an anonymous function.

Consider the example shown below −

 Live Demo

void main() {
   var fruits = ["Apple", "Mango", "Banana", "Kiwi"];
   fruits.forEach((item) {
      print('${fruits.indexOf(item)}: $item');
   });
}

In the above example, we have an anonymous function with an untyped parameter named item.

Output

0: Apple
1: Mango
2: Banana
3: Kiwi
raja
Published on 21-May-2021 12:33:47
Advertisements