Dart Anonymous Functions: Higher-Order Functions with Collections

Dart Anonymous Functions: Higher-Order Functions with Collections

Table of contents

An anonymous function in Dart is like named function but they do noy have names associated with it.

An anonymous function can have zero or more parameters with optional type annotations.

  • In dart most of the functions are named functions we can also create nameless function knows as an anonymous function, lambda, or closure.

  • In dart we can assign any anonymous function to constants or variables, later we can access or retrieve the value of closure based on our requirements.

High Order Function:

When a function returns another function ,it is referred to as a High Order Function, or When a function takes parameter as a function, it is called a higher-order function.

In this example, we are using a lambda function to demonstrate how a higher-order function works.

  • In main(), we define a lambda function addTwoNumbers using the syntax (int a, int b) => a + b. This function takes two integers as input parameters a and b, and it returns their sum.

  • addTwoNumbers is then passed as an argument to the higher-order function myNewFunction.

  • The myNewFunction function takes a string msg and a function summation as parameters. It prints the message msg and then calls the summation function with 6 and 7 as arguments, printing the result.

  • This demonstrates the use of lambda functions (anonymous functions) and higher-order functions in Dart. Lambda functions are convenient for short, simple functions, and higher-order functions allow for functions to be passed around as arguments or returned from other functions.