Anonymous Functions

Anonymous functions, also known as lambda functions or closures, are functions without a name. They're like having a helper that does a specific task but doesn't need a formal introduction!

In Dart, anonymous functions are incredibly useful when you need a quick function for a short-term task, especially when working with collections or passing functions as parameters.

Basic Syntax

The basic syntax for an anonymous function in Dart is:

(parameters) {
  // function body
  return value; // optional
}

Or for single expressions, you can use the arrow syntax:

(parameters) => expression

Simple Examples

Here's a basic anonymous function that adds two numbers:

var add = (int a, int b) {
  return a + b;
};

print(add(5, 3)); // Output: 8

Using arrow syntax for the same function:

var add = (int a, int b) => a + b;
print(add(5, 3)); // Output: 8

Anonymous Functions with Collections

Anonymous functions shine when working with lists and other collections. Here are some common use cases:

Using forEach()

var fruits = ['apple', 'banana', 'orange'];

fruits.forEach((fruit) {
  print('I love $fruit');
});

// Output:
// I love apple
// I love banana
// I love orange

Using map()

var numbers = [1, 2, 3, 4, 5];

var doubled = numbers.map((number) => number * 2).toList();
print(doubled); // Output: [2, 4, 6, 8, 10]

Using where() for filtering

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var evenNumbers = numbers.where((number) => number % 2 == 0).toList();
print(evenNumbers); // Output: [2, 4, 6, 8, 10]

Passing Anonymous Functions as Parameters

You can pass anonymous functions to other functions, making your code more flexible:

void processNumbers(List<int> numbers, Function processor) {
  for (var number in numbers) {
    processor(number);
  }
}

var numbers = [1, 2, 3, 4, 5];

// Pass an anonymous function that prints squares
processNumbers(numbers, (num) {
  print('Square of $num is ${num * num}');
});

Capturing Variables (Closures)

Anonymous functions can "capture" variables from their surrounding scope, creating closures:

String createGreeting(String name) {
  return (String message) => 'Hello $name, $message';
}

var greetJohn = createGreeting('John');
print(greetJohn('how are you?')); // Output: Hello John, how are you?

When to Use Anonymous Functions

Anonymous functions are perfect when you need:

  • Quick, one-time operations on collections
  • Event handlers or callbacks
  • Short functions that don't warrant a separate named function
  • Functions that capture local variables (closures)

Think of anonymous functions as your coding Swiss Army knife - compact, versatile, and always ready when you need a quick solution!