Function scoping

suggest change

Dart functions may also be declared anonymously or nested. For example, to create a nested function, just open a new function block within an existing function block.

void outerFunction() {
    void innerFunction() {
        /// Does stuff
    }
}

The function innerFunction may now be used inside, and only inside, outerFunction. No other function has access to it.

Functions in Dart may also be declared anonymously, which is commonly used as function arguments. A common example is the sort method of a List. This method takes an optional argument with the following signature:

int compare(E a, E b)

The documentation states that the function must return 0 if a and b are equal, a negative integer if a < b, and a positive integer if a > b.

Knowing this, we can sort a list of integers using an anonymous function.

List<int> numbers = [4,1,3,5,7];

numbers.sort((int a, int b) {
   if(a == b) {
      return 0;
   } else if (a < b) {
      return -1;
   } else {
      return 1;
   }
});

An anonymous function may also be bound to an identifier:

int Function(int, int) intSorter = (int a, int b) {
   if(a == b) {
      return 0;
   } else if (a < b) {
      return -1;
   } else {
      return 1;
   }
};

and used as an ordinary variable.

numbers.sort(intSorter);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents