Dart Anonymous Functions

Creating functions without names for flexible programming

🎭 What are Anonymous Functions?

Anonymous functions in Dart are functions without names, also called lambda functions. They're perfect for short operations and can be passed as arguments to other functions.


// Regular named function
void sayHello() {
  print('Hello!');
}

// Anonymous function stored in variable
var greet = () {
  print('Hello from anonymous function!');
};

greet(); // Call the anonymous function
                                    

Output:

Hello from anonymous function!

Anonymous Function Features

🏷️

No Name Required

Functions without identifiers

var multiply = (int a, int b) {
  return a * b;
};
📦

Store in Variables

Assign to variables for reuse

var isEven = (int n) => n % 2 == 0;
print(isEven(4)); // true
🔄

Pass as Arguments

Use as parameters to other functions

numbers.where((n) => n > 5);
list.map((item) => item.toUpperCase());

Inline Usage

Define and use immediately

var result = ((int x) => x * x)(5);
// result = 25

🔹 Basic Anonymous Functions

Different ways to create and use anonymous functions:

void main() {
  // Anonymous function with multiple statements
  var calculator = (String operation, double a, double b) {
    switch (operation) {
      case 'add':
        return a + b;
      case 'subtract':
        return a - b;
      case 'multiply':
        return a * b;
      case 'divide':
        return b != 0 ? a / b : 0;
      default:
        return 0;
    }
  };
  
  // Anonymous arrow function
  var square = (double n) => n * n;
  var greet = (String name) => 'Hello, $name!';
  
  // Using the functions
  print('5 + 3 = ${calculator('add', 5, 3)}');
  print('5 * 3 = ${calculator('multiply', 5, 3)}');
  print('Square of 4: ${square(4)}');
  print(greet('Alice'));
}

Output:

5 + 3 = 8.0

5 * 3 = 15.0

Square of 4: 16.0

Hello, Alice!

🔹 Anonymous Functions with Collections

Using anonymous functions with list operations:

void main() {
  var fruits = ['apple', 'banana', 'cherry', 'date'];
  var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  
  // Transform with anonymous functions
  var upperFruits = fruits.map((fruit) {
    return fruit.toUpperCase();
  }).toList();
  
  var squaredNumbers = numbers.map((n) => n * n).toList();
  
  // Filter with anonymous functions
  var longFruits = fruits.where((fruit) {
    return fruit.length > 5;
  }).toList();
  
  var evenNumbers = numbers.where((n) => n % 2 == 0).toList();
  
  // Process each item
  print('=== Fruits Processing ===');
  fruits.forEach((fruit) {
    print('Processing: $fruit (${fruit.length} letters)');
  });
  
  print('\nResults:');
  print('Upper fruits: $upperFruits');
  print('Squared numbers: $squaredNumbers');
  print('Long fruits: $longFruits');
  print('Even numbers: $evenNumbers');
}

Output:

=== Fruits Processing ===

Processing: apple (5 letters)

Processing: banana (6 letters)

Processing: cherry (6 letters)

Processing: date (4 letters)


Results:

Upper fruits: [APPLE, BANANA, CHERRY, DATE]

Squared numbers: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Long fruits: [banana, cherry]

Even numbers: [2, 4, 6, 8, 10]

🔹 Anonymous Functions as Parameters

Passing anonymous functions to other functions:

// Function that takes another function as parameter
void processNumbers(List numbers, Function(int) processor) {
  print('Processing numbers...');
  for (int number in numbers) {
    processor(number);
  }
}

// Function that returns a function
Function createMultiplier(int factor) {
  return (int n) => n * factor;
}

void main() {
  var numbers = [1, 2, 3, 4, 5];
  
  // Pass anonymous function as parameter
  processNumbers(numbers, (int n) {
    print('Number: $n, Square: ${n * n}');
  });
  
  print('\n--- Using Function Factory ---');
  
  // Create functions using factory
  var double = createMultiplier(2);
  var triple = createMultiplier(3);
  
  print('Double 5: ${double(5)}');
  print('Triple 4: ${triple(4)}');
  
  // Inline anonymous function
  var sum = numbers.fold(0, (prev, curr) => prev + curr);
  print('\nSum of numbers: $sum');
}

Output:

Processing numbers...

Number: 1, Square: 1

Number: 2, Square: 4

Number: 3, Square: 9

Number: 4, Square: 16

Number: 5, Square: 25


--- Using Function Factory ---

Double 5: 10

Triple 4: 12


Sum of numbers: 15

🧠 Test Your Knowledge

What is another name for anonymous functions?