Dart Anonoymous Functions: Higher-Order Functions with Collections

Dart Anonoymous Functions: Higher-Order Functions with Collections

ยท

2 min read

1. Dart Anonymous Functions:

In Dart, anonymous functions are functions without a name. They are often used for short, one-time operations and can be assigned to variables or passed as arguments to other functions.

Example: Using an Anonymous Function:

void main() {
    // Anonymous function assigned to a variable
    var greet = () {
        print('Hello, Dart!');
    };

    // Calling the anonymous function using the variable
    greet(); // Output: Hello, Dart!
}

In this example, we've created an anonymous function and assigned it to the variable greet. Then, we invoke the function by calling greet().

2. Higher-Order Functions with Collections:

Higher-order functions are functions that either take other functions as parameters or return functions. Dart's support for higher-order functions is particularly useful when working with collections like lists.

Example: Using Higher-Order Functions with a List:

void main() {
    List<int> numbers = [1, 2, 3, 4, 5];

    // Using forEach as a higher-order function
    numbers.forEach((number) {
        print('Doubled: ${number * 2}');
    });
}

In this example, forEach is a higher-order function that takes an anonymous function as a parameter. The anonymous function is applied to each element of the numbers list, doubling each value and printing the result.

By combining anonymous functions and higher-order functions, Dart allows for concise and expressive code, especially when working with collections. These features make Dart a powerful language for tasks involving data manipulation and transformation.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย