Anonymous functions

Most functions are named, such as main() or printElement().You can also create a nameless functioncalled an anonymous function, or sometimes a lambda or closure.You might assign an anonymous function to a variable so that,for example, you can add or remove it from a collection.

An anonymous function looks similar to a named function—zero or more parameters, separated by commasand optional type annotations, between parentheses.

The code block that follows contains the function’s body:

([[Type] param1[, …]]) { codeBlock; };

The following example defines an anonymous function with an untyped parameter, item.The function, invoked for each item in the list,prints a string that includes the value at the specified index.

  1. var list = ['apples', 'bananas', 'oranges'];
  2. list.forEach((item) {
  3. print('${list.indexOf(item)}: $item');
  4. });

Click Run to execute the code.

If the function contains only one statement, you can shorten it using arrownotation. Paste the following line into DartPad and click Run to verify thatit is functionally equivalent.

  1. list.forEach(
  2. (item) => print('${list.indexOf(item)}: $item'));