Clousers & Scope | Lexical Cloures in Dart

Clousers & Scope | Lexical Cloures in Dart

ยท

2 min read

  • I simple terms we can say that Clourse is one type of the function object which has access the in the lexical scope even it's the function is used outside of the original scope.

In below example we can see that first we have declare a variable in void main function than we create new function called Outer and again we called a as variable but this time we do not require to use any keyword to declare a due to we already declare in outside the function , so we can access the a from our lexical scope.

void main()
{
  var a = 0;
  print("The value of A is : $a");

  void Outer()
  {
    var a =10;
    print("The Value of A in Outer Function is : $a");
  }

 Outer();
}

//The value of A is : 0
//The Value of A in Outer Function is : 10

In below example , we have declared the var a in outside the function it become global variable , so it can be access by any function , even it outside of the function or inner in the function .

In here , we can see that , first we have declare a in outside of the function , that we print a value in the void main function , than again we create Outer function inside the void main function and modified the value of a 0 to 10 , after that again we have create one more function called New outside the main function and modified the a value to 20 , and we can see the output of all three function , without any error.

  • In here, we declare a only one time in outside of the all function and after that we only call a value and modified it and still we did not face any error in our program,
var a = 0;

void main()
{
  print("The value of A is : $a");

  void Outer()
  {
    var a =10;
    print("The Value of A in Outer Function is : $a");
  }

 Outer();
 New();
}

void New()
 {
a = 20;
print("The Value of A in new Function is : $a ");
 }
/** 
The value of A is : 0
The Value of A in Outer Function is : 10
The Value of A in new Function is : 20 
*/

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย