Scope controls the visibility of variables. It determines where in your code a variable can be seen and used. Understanding this prevents "undefined variable" errors.
1. Global vs Local Scope
Scope is defined by curly braces {}. Variables declared at the top level are "Global". Variables declared inside braces are "Local".
Visibility Rules
1String globalVar = 'I am everywhere';2 3void main() {4 String localVar = 'I am only in main';5 6 print(globalVar); // ✅ Accessible7 print(localVar); // ✅ Accessible8}9 10void otherFunction() {11 print(globalVar); // ✅ Accessible12 // print(localVar); ❌ Error: undefined name 'localVar'13}HintAvoid Global variables in large apps. They make it hard to track who is changing the data.
2. Block Scope
Dart blocks (if statements, loops, or bare {}) create their own scope. Variables born inside a block die when the block ends.
Temporary Variables
1void main() {2 if (true) {3 int insideIf = 99;4 print(insideIf);5 }6 7 // print(insideIf); ❌ Error: The variable is gone.8 9 // Loops10 for (int i = 0; i < 5; i++) {11 // 'i' only exists inside this loop12 }13 // print(i); ❌ Error14}HintThis is great for memory management. Temporary variables are cleaned up automatically.
3. Variable Shadowing
If you name a local variable the same as an outer variable, the local one "shadows" (hides) the outer one.
Shadowing Pitfall
1String name = 'Global Bob';2 3void main() {4 String name = 'Local Alice'; // Shadows 'Global Bob'5 6 print(name); // Prints 'Local Alice'7 8 // You cannot access 'Global Bob' here anymore using 'name'9}HintShadowing often leads to bugs where you think you are updating a class variable but are actually updating a local temporary variable.
4. Lexical Scope
Dart looks "outwards" to find variables. It checks the current block, then the parent block, then the grandparent, all the way to global.
Looking Outwards
1void main() {2 bool isSunny = true;3 4 void nestedFunction() {5 if (isSunny) { // ✅ Looks up to find 'isSunny'6 print('Go outside');7 }8 }9}HintInner functions typically "capture" the variables they need from their surrounding environment.
Loot collected
Key takeaways- Global variables exist everywhere; Local variables exist only in their block
{}. - Inner blocks can access variables from outer blocks, but not vice-versa.
- Use local variables whenever possible to keep code clean and prevent bugs.
- A variable dies when its code block
{}ends.
Side quests
Practice exercises
Exercise 1: Access Check
If you define var x = 10 inside main(), can a separate function test() access it?
Reveal solutionHide solution
1No, because `x` is local to `main`.Exercise 2: Global Fix
Where should you move a variable so that ALL functions can see it?
Reveal solutionHide solution
1Move it outside of all functions, to the top level of the file.