Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Scope


Share

Dart Scope

The scope of a variable is the part of the code where you can use it.

In Dart, the scope is decided by the curly brackets {}.

A variable exists from the line where it is declared to the end of its block.

A block is the code between an opening { and the matching }.


Local Variables

A variable that is declared inside a function is a local variable.

It can only be used inside that function:

Example

void showCar() {
  var car = 'Volvo';
  print(car);
}

void main() {
  showCar();
}
Try it Yourself »

Result:

Volvo

If you try to use car outside of showCar(), you get an error:

Example

void showCar() {
  var car = 'Volvo';
  print(car);
}

void main() {
  showCar();
  print(car);
}
Try it Yourself »

Result:

main.dart:8:9: Error: Undefined name 'car'.
  print(car);
        ^^^


Block Scope

Every block has its own scope, even the blocks of if statements and loops.

A variable declared inside an if block only exists inside that block:

Example

void main() {
  var age = 20;

  if (age >= 18) {
    var message = 'Welcome';
    print(message);
  }

  print(message);
}
Try it Yourself »

Result:

main.dart:9:9: Error: Undefined name 'message'.
  print(message);
        ^^^^^^^

To use the value after the block, declare the variable before the block:

Example

void main() {
  var age = 20;
  var message = 'Too young';

  if (age >= 18) {
    message = 'Welcome';
  }

  print(message);
}
Try it Yourself »

Result:

Welcome

The loop variable of a for loop also belongs to the loop only:

Example

void main() {
  for (var i = 1; i <= 3; i++) {
    print('Round $i');
  }
  // i does not exist here
}
Try it Yourself »

Result:

Round 1
Round 2
Round 3

Top-Level Variables

A variable that is declared outside of all functions is a top-level variable.

It can be used everywhere in the file, in every function:

Example

var appName = 'Score Keeper';

void showTitle() {
  print('Welcome to $appName');
}

void main() {
  showTitle();
  print(appName);
}
Try it Yourself »

Result:

Welcome to Score Keeper
Score Keeper

Tip: Use top-level variables only when you really need them.

Local variables are easier to follow, because only one function can change them.


Lexical Scope

Dart uses lexical scope.

This means that you can see where a variable can be used just by reading the code.

An inner block can use the variables of all the blocks around it:

Example

var brand = 'Ford';

void main() {
  var model = 'Mustang';

  void showCar() {
    var year = 1969;
    print('$brand $model $year');
  }

  showCar();
}
Try it Yourself »

Result:

Ford Mustang 1969

The function showCar() is declared inside main(), so it can use model from main() and the top-level variable brand.

But main() cannot use year, because it belongs to the inner function.


Shadowing

An inner block can declare a variable with the same name as a variable in an outer block.

This is called shadowing, because the inner variable hides the outer one:

Example

var color = 'red';

void paint() {
  var color = 'blue';
  print('In paint(): $color');
}

void main() {
  paint();
  print('In main(): $color');
}
Try it Yourself »

Result:

In paint(): blue
In main(): red

Inside paint(), the name color means the local variable.

The top-level variable is not changed, so main() still sees 'red'.

The same happens with an inner block inside a function:

Example

void main() {
  var x = 10;

  {
    var x = 20;
    print('Inside: $x');
  }

  print('Outside: $x');
}
Try it Yourself »

Result:

Inside: 20
Outside: 10

Note: Shadowing can make code hard to read.

It is better to give different variables different names.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.