×

Dart Anonymous Function

Dart functions are the user defined functions that are designed to perform specific task. The use case of the functions is that they can be directly called any number of times in a program wherever required without having to write the same lines of code again and again. So far, we have understood the named user-defined functions. But Dart also supports the nameless functions i.e., the functions that do not have any name. Such functions are also known as anonymous functions, lambda functions or closure.

Anonymous functions have similar features to the regular function with the only difference of it not having name. They can have either no arguments or any number of arguments with an optional type annotation. They can be assigned to a variable and then the value of closure can be retrieved or accessed as per the need. They contain an independent block of the code, which can be passed around in our code as function parameters. The syntax is as follows.

Syntax :

( parameter_list ) {  

   statement( s ) 

}

Let's consider the following example.

Program

void main( ) 

{   

  var list = [ " Yukta ", " Tushar ", " Divya ", " Atharva " ] ; 

  print( " Example of anonymous function " ) ; 

  list.forEach( ( item ) { 

      print( ' ${ list.indexOf( item ) } : $item ' ) ; 

} ) ;   

Output :

Example of anonymous function

0 :  Yukta

1 :  Tushar

2 :  Divya

3 :  Atharva

Explanation:

The above example lists a user defined anonymous function with a single type argument 'item'. This function called for each and every time in the list and printed the strings initialized in the list with its specified index value.

If we were to confine the function in just one statement, then the above code could be written as follows :

list.forEach(  ( item ) => print( " ${ list.indexOf( item ) } : $item " ) ) ; 

This code is pretty much equivalent to this above snippet. It can be verified by pasting it in the above Dart code and compile.

Lexical Scope

The lexical scope is a term used in various programming languages that describes a condition where the scope of the variable is not present when the control is out of the block of the code where the scope was present just now.

Dart is a lexically scoped language. The scope of the variable is decided at the time of compilation. The variable behaves differently if defined in the different curly braces. In order to determine the scope of the variable, trace all the braces and stop where that variable exists.

Let's understand the lexical scope using the following example.

Program

/* declaring a global variable that is outside the all functions

It can be accessed throughout the whole program */

var global = 10 ;




void main( ) {

  /* this is the local variable to the function main( )

   It is accessible only within the main( ) function. */

  var local = 5;




  print(global);

  print(local);

 

  void func( ) {

   /* this is the local variable to the function func( )

   It is accessible within the function func( ) and func1( ). */

    var func_var = 1;

    print(func_var);

    print(local);

    print(global);

 

    void func1( ) {

    /* this is the local variable to the function main( )

     It is accessible within the function func1( ) and func( ). */

      var func1_var = 2;

      print(func1_var);

      print(func_var);

      print(local);

      print(global);

      }

  }

}

Output:

10

5

Lexical Closure

A lexical closure is a way by which we implement lexical scope name binding in a function. It is a function object that has access to variables in its lexical scope even when the function is used of its original scope. In other words, it provides access to an outer function's scope from the inner function. Let's understand the following example.

Program

/* a function that accepts the value of local from 

main( ) and prints it */

void func(int local ) {

   

    var func_var = 1 ;

    print( func_var ) ;

    print( local ) ;

  }

 

void main( )

{

  // initializing the local variable with value 5

  var local = 5 ;




  func( local ) ;

}

Output:

1

5

Related Topics

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Dart - extends, with and implements Keywords

The application development in Dart programming language using the Flutter framework, regularly experience different usage of the implements, extends and with keywords. Dart has full support for inheritance that is...

5 minutes read.

Callable Classes in Dart

Just like the functions, we can also call the instances of classes in Dart. Such classes are also known as “callable ” classes. We need to use the “call( )”...

3 minutes read.

Dart - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart Break and Continue

Loop statements are used to change the normal sequence of flow of the program. Dart supports two types of loop control statements: Break StatementContinue Statement Break Statement : The ‘ break ’ statement is...

4 minutes read.

Dart Booleans

Booleans Dart has a data type named ‘bool’ to represent Boolean values : true and false, which are compile-time constants. ‘True’ or ‘False’ cannot be assigned with values 1 or 0. Example, bool...

1 minute read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Generics

Dart Generics is similar to Dart collections, which are used to store homogeneous data. As we have discussed in Dart's features, it is a language with types being optional. By default,...

4 minutes read.

Dart If-else statement

In the previous section, we studied about if statements in detail. If – block is executed when the condition evaluates to true, else if the condition evaluates to false, then...

1 minute read.

Dart Concurrency

Dart concurrency allows us to run multiple or multiple components of a system at once. It issues several commands at once. Dart provides Isolates as a tool for performing compliance...

2 minutes read.

Dart Assignment Operator

Assignment operators are the operators that assign value to the variables. The value on the right-hand side is assigned to the variable on the left-hand side. We can also use...

4 minutes read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 minutes read.

Dart Loops

Looping refers to repeating or reusing the same lines of code repeatedly until a particular test condition evaluates to true. It is also known as iterating.  It is effectively used when...

4 minutes read.