Anonymous Functions and Closures

  • Anonymous Functions and Closures

Anonymous Functions in Dart

Anonymous Function in dart is also known as lambda expressions or function literals it does not have any name for the function. They are used for inline and are for small operations.

Example

void main() {
  var list = ['hello', 'world'];

  // Using an anonymous function
  list.forEach((item) {
    print(item);
  });
}

output

hello
world

Closure Functions

A Closure is a function object that has access to variable in its lexical scope, even when the function is used of its original scope. This means a closure can “close over” variables definedd outside ots body. Example

void main() {
  var counts = createCount();
  print(counts()); // Output: 1
  print(counts()); // Output: 2
}

Function createCount() {
  var count = 0;

  return () {
    count += 1;
    return count;
  };
}