Skip to main content
An anonymous function, often referred to as a lambda or closure, is a function literal defined without an identifier. In Dart, functions are first-class objects; consequently, anonymous functions are values that can be assigned to variables, passed as arguments, or returned from other functions.

Basic Syntax

The syntax consists of a parenthesized parameter list followed by a block body. When used as a value (such as in an assignment), the statement is terminated by a semicolon.
(parameters) {
  statements;
  return expression; // Optional
}
Example:
// Assigning an anonymous function to a variable
final printUser = (String name, int age) {
  print('User: $name, Age: $age');
};

Arrow Syntax

If the function body consists of a single expression, Dart provides a shorthand “arrow” syntax. This notation implies a return statement and omits the braces.
(parameters) => expression;
Example:
final add = (int a, int b) => a + b;

Parameter Typing and Inference

Parameters can be explicitly typed or left untyped. When types are omitted, Dart infers the parameter types based on the context, such as the type of the variable to which the function is assigned. Explicit Typing:
final explicit = (String item) {
  return item.toUpperCase();
};
Type Inference:
// The variable type 'bool Function(String)' provides context.
// Dart infers that 'item' is of type String.
final bool Function(String) isLong = (item) {
  return item.length > 5;
};

Lexical Scope and Closures

Anonymous functions act as closures, meaning they capture variables from their surrounding lexical scope. The function retains access to these variables even when executed outside their original definition scope.
var multiplier = 2;

// This function captures 'multiplier' from the surrounding scope
final calculate = (int value) {
  return value * multiplier;
};

Immediate Invocation

An anonymous function can be defined and executed immediately without being assigned to a variable.
// Defines and invokes the function immediately with the argument 10
((int x) => print(x * x))(10);
Master Dart with Deep Grasping Methodology!Learn More