Dart

Dart Variable Scopes

Dart Variable Scopes

In this tutorial, we will learn about Dart variable scopes. A variable’s scope refers to the region of the code where it is visible and can be accessed. The scope of a variable is determined by where it is declared.

Dart language supports different types of variable scopes. They are as follows:

  • Block Scope
  • Function Scope
  • Class Scope
  • Global Scope

Block Scope

Variables declared inside a block of code (i.e., within curly braces {}) have block scope. These variables are accessible only within that block and any nested blocks inside it. Once you leave the block, the variable is no longer accessible.

Example:

void exampleFunction() {
int x = 10; // Block scope starts here

if (x > 5) { // Nested block scope starts here
  int y = 20;
  print(x); // Accessible
 print(y); // Accessible
} // Nested block scope ends here

 

print(x); // Still accessible
// print(y); // Not accessible, ‘y’ is not in this scope
} // Block scope ends here

 

Function Scope

Variables declared inside a function have function scope. They are accessible only within that function and not visible outside of the function.

Example:

void exampleFunction() {
int x = 10; // Function scope starts here
print(x); // Accessible

if (x > 5) {
  int y = 20;
  print(y); // Accessible
}

// print(y); // Not accessible, ‘y’ is not in this scope
} // Function scope ends here

 

Class Scope

Variables declared as class members (outside of any method) have class scope. They are accessible within all methods of the class.

Example:

class MyClass {
int number = 79; // Class scope variable

void print() {
  print(number); // Accessible within the class
}
}

 

Global Scope

Variables declared at the top level (outside of any function or class) have global scope. They are accessible throughout the entire Dart file.

Example:

int global_x = 23; // Global scope variable

void main() {
       print(global_x); // Accessible here
}

 

It’s important to note that Dart also supports shadowing, which means that a variable declared in an inner scope can hide a variable with the same name declared in an outer scope. This can lead to unexpected behavior, so it’s essential to be cautious when using the same variable names in different scopes.

 

Dart Tutorials

Dart tutorial on this website can be found at: