What are Lambda Functions?
Lambda functions, also known as anonymous functions or function literals, are functions that are not bound to an identifier (they don't have a name). They are often used as short, disposable functions that are passed as arguments to higher‑order functions or assigned to variables. Lambdas are a key feature of functional programming and are widely used in Dart, especially when working with collections.
Syntax of Lambda Functions
Dart supports two syntaxes for lambda functions: block body and arrow syntax (fat arrow). Both can capture variables from their surrounding scope.
Block Body Syntax
For example:
Arrow Syntax (Fat Arrow)
For single‑expression functions, you can use the arrow syntax =>. The result of the expression is implicitly returned.
Assigning Lambdas to Variables
Lambdas are first‑class objects, so you can assign them to variables and use them like any other value.
Passing Lambdas as Arguments
This is the most common use case. Many Dart methods accept functions as parameters, such as forEach, map, where, reduce, and fold. You can pass a lambda directly.
Closures – Capturing Variables
A closure is a lambda that captures variables from the scope where it was defined. It 'closes over' those variables, keeping them alive even after that scope exits. This is a powerful feature for creating stateful functions.
In this example, each invocation of makeCounter creates a new closure with its own count variable. The lambda captures count and increments it each time.
Using Lambdas with Callbacks
Lambdas are ideal for short‑lived callbacks, such as event handlers in UI programming (e.g., Flutter).
Lambda vs Named Function
- Named functions are reusable, can be called from anywhere, and are easier to debug (they appear in stack traces).
- Lambdas are more concise and can capture local variables easily; they are perfect for one‑off operations.
Key Takeaways
- Lambdas (anonymous functions) are functions without a name.
- Syntax: block body
(p) { ... }or arrow(p) => expr.
- Syntax: block body
- They can be assigned to variables, passed as arguments, and returned from other functions.
- Closures capture variables from the surrounding scope, enabling stateful behavior.
- Widely used with collection methods (
forEach,map,where, etc.) and in event‑driven programming.
- Widely used with collection methods (