Scope
Prerequisites: Functions
Scope is the region of code where a name can be used. Every pair of curly braces creates a new scope.
Real-world analogy: scopes are nested rooms. From an inner room you can see into the rooms around it, but people outside can't see in.
Example
const taxRate = 0.2; // top level: visible everywhere in the file
double total(double price) {
final tax = price * taxRate; // inner code can see outer names
return price + tax;
}
void main() {
print(total(100));
if (true) {
final message = 'inside';
print(message);
}
}
120.0
inside
taxRateis declared at the top level, so every function can use it.taxexists only insidetotal.messageexists only inside theifbraces.
Using a name outside its scope is a compile error:
void main() {
if (true) {
final message = 'inside';
}
print(message);
}
hello.dart:5:9: Error: Undefined name 'message'.
Library privacy
Top-level names starting with an underscore, like _cache, are private
to their library (usually one file). Other files can't see them —
Dart's simple form of access control.
Keep scope small
Declare values close to where they're used, and pass values into functions as parameters instead of reading many top-level variables. Mutable top-level variables in particular make programs hard to follow.