Scope in Dart
Scope In Dart
The scope is a concept that refers to where values can be accessed or referenced. Dart uses curly braces {} to determine the scope of variables. If you define a variable inside curly braces, you can’t use it outside the curly braces.
Method Scope
If you created variables inside the method, you can use them inside the method block but not outside the method block.
Example
void main() {
String method = "I am Method. Anyone can't access me.";
print(method);
}
In this program, method
is String type where you can accessed and print method only inside the main function but not outside the main function.
Global Scope
You can define a variable in the global scope to use the variable anywhere in your program.
Example
String global = "I am Global. Anyone can access me.";
void main() {
print(global);
}
In this program, the variable named global
is a top-level variable; you can access it anywhere in the program.
Local Scope
You can define a variable in the local scope to use the variable inside curly braces in your program.
Example
void main() {
int age = 20;
}
void printInfo(){
print("Age is $age"); // error
}
In this program, the variable named age
is local; you can access it only inside the curly bracket of main method.
Note: Define your variable as much as close [Local] as you can. It makes your code clean and prevents you from using or changing them where you shouldn’t.