Skip to main content
An anonymous method in Dart (often referred to as an anonymous function, lambda, or closure) is a nameless, first-class function object. It encapsulates a block of code or a single expression that can be assigned to a variable, passed as an argument to a higher-order function, or returned from another function.

Syntax

Dart supports two syntactic forms for anonymous methods: block body and expression body (arrow syntax). Block Body Syntax: Requires an explicit return statement to yield a value. If no return is provided, the method implicitly returns null.
(Type param1, Type param2) {
  // statements
  return expression;
}
Expression Body Syntax: Uses the fat arrow (=>) operator. It evaluates and implicitly returns a single expression. It cannot contain statements (like if or for).
(Type param1, Type param2) => expression;

Technical Mechanics

Type Inference Dart’s static analyzer infers the parameter types and the return type of an anonymous method based on its assignment or invocation context. If a strict context is provided (such as a strongly typed variable or a higher-order function signature), explicit type annotations for parameters can be omitted, and the analyzer will deduce them. If no context is provided (e.g., assigning to var without parameter types), the parameters default to dynamic.
// Explicitly typed parameters (no external context required)
var add = (int a, int b) {
  return a + b;
};

// Context-based inference via variable type signature
// The analyzer infers 'a' and 'b' as int based on the left-hand side context.
int Function(int, int) multiply = (a, b) => a * b; 

// Context-based inference via higher-order function
// The analyzer infers 'a' and 'b' as int based on the List<int>.reduce signature.
final sum = [1, 2, 3].reduce((a, b) => a + b);
Lexical Closures Anonymous methods in Dart inherently act as lexical closures. They capture and retain references to variables defined in their surrounding lexical scope at the time of their creation. The anonymous method maintains access to these captured variables even if it is executed outside of its original scope.
Function createCounter(int step) {
  int count = 0;
  // The anonymous method captures both 'step' and 'count'
  return () {
    count += step;
    return count;
  };
}
Parameter Handling Anonymous methods follow the same parameter rules as named functions. They support zero or more required positional parameters, optional positional parameters ([Type param]), and named parameters ({Type param}).
// Anonymous method with optional named parameters
var formatData = (String data, {bool uppercase = false}) {
  return uppercase ? data.toUpperCase() : data;
};
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More