Dart is a lexical-scope language. What does it mean? The variable has only access to a block where it is defined.

Let’s discuss the lexical scope of variables and usage in Closure function objects.

What is the Lexical Scope in Dart?

Variables/Closure functions are only accessed inside the same block that is defined.

A variable declared in curly braces is available to access inside the same block as well as nested scopes.

You can define the nested blocks using {} or functions

In Dart, Block, or {} define the scope

In the Dart file, Variables declared outside the main function are global variables Global Variables are accessible to all functions including the main function

bool enabled = true; // global scope

void main() {
  print(enabled);

}

Let’s declare the variable inside the main function

This variable declared in the main function is not available in the global scope

bool enabled = true; // global scope

void main() {
  bool enabledMain=false; // main scope variable
  print(enabled);
  print(enabledMain);

}

Let’s define one more inner function inside the main function.

Child functions can access parent function scope variables.

bool enabled = true; // global scope

void main() {
  bool enabledMain = false;
    print(enabled); // true
    print(enabledMain); //false
  String str = "john";

  void innerMain() {
    // local scope variable

    print(enabled); // true
    print(enabledMain); //false

    print(str); //john
  } //end inner scope

  innerMain();
}

Dart Lexical closure example

A closure function is an object that has access to a variable defined in lexical scope.

Closure functions can access variables outside or surrounding the scope

The following example

sum function takes the sumBy variable, which accepts variables from outside the scope

Function sum(num sumBy) {
  return (num n) => sumBy + n;
}

void main() {
  var add10 = sum(10);

  var add5 = sum(5);

  print(add10(8)); // 18
  print(add10(31)); // 41
}