×

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

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 Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute 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 Keywords

Keywords are the reserved words of a programming language, and they have a special meaning that comes defined by the language. These cannot be used as an identifier, and all...

1 minute read.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

2 minutes read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

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 Queues

A queue is a user-defined collection of data. It is based on the FIFO principle ( First In First Out ) which implies that the element to be inserted first,...

3 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 minutes read.

Interfaces in Dart

An interface in Dart refers to the syntax or blueprint that any class must adhere to. It basically defines the array of methods available on the object. It provides the...

3 minutes read.

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development...

6 minutes read.

Dart Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

4 minutes read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Dart Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform...

6 minutes read.

Dart Numbers

Dart provides an in-built data type ‘Numbers’ that provides two types of values: intdouble 1. int data type int data type supports integer values, and their size or values range is platform-dependent. Integers...

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.

Lexical Scope and Closure

Lexical Scope : Lexical scope is a very important term in any programming language. It defines the scope of the variable based on the block it is contained inside. According to...

2 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 Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

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.