Dart Anonymous Functions (original) (raw)

Last Updated : 28 Mar, 2025

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.

**Syntax:

(parameter_list) {
statement(s)
}

Anonymous Function in forEach()

**Example:

Dart `

// 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:

Dart `

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:

15

Using an Anonymous Function as a Callback

Anonymous functions are widely used in **asynchronous operations like button clicks or API calls.

**Example:

Dart `

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