Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 61 ยท Getting Started

Variables, var, final and const

Learn how Dart stores values: type inference with var, explicit types, final versus const, compile-time constants and an introduction to late variables.

A variable is a named place that holds a value. Dart gives you several ways to declare one, and the choice tells both the compiler and the next reader something important: can this value change, and when is it known? You will use var, final and const in almost every file you ever write, so it pays to understand the difference early.

Dart snippets here are read-only. TypeScript stand-ins let you run the equivalent ideas, with notes where the two languages differ.

Declaring a variable

The most direct form names the type:

DART
void main() {
  String city = 'Lisbon';
  int visitors = 1200;
  double rating = 4.7;
  bool open = true;

  print('$city: $visitors visitors, rating $rating, open: $open');
}
TEXT
Lisbon: 1200 visitors, rating 4.7, open: true

Writing every type is allowed but often unnecessary. With var, the compiler works out the type from the value on the right:

DART
void main() {
  var city = 'Lisbon';   // inferred as String
  var visitors = 1200;   // inferred as int
  var rating = 4.7;      // inferred as double

  visitors = visitors + 50;   // fine, still an int
  // city = 42;               // error: an int can't be assigned to a String
}

var does not mean "any type". Once the compiler infers String for city, the variable is a String forever. The type is fixed; only the value changes. The Dart style guide recommends var for local variables when the type is obvious from the right-hand side, and explicit types for public APIs.

TypeScript Inference fixes the type (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Uninitialized variables and null

A variable that is declared but not given a value starts as null, but only if its type allows null. A type allows null when it ends with a question mark:

DART
void main() {
  int? score;          // nullable, starts as null
  print(score);        // null

  score = 10;
  print(score);        // 10
}

Without the ?, Dart requires the variable to have a value before you read it. The lesson on null safety explains this in depth. One more beware: var x; with no value and no type gives the variable the special type dynamic, which turns off type checking for it. Avoid that.

final: assign once

final means the variable can be assigned exactly one time. After that it cannot be reassigned. The value does not have to be known when you write the code; it can be computed while the program runs.

DART
void main() {
  final name = 'Ada';             // type inferred as String
  final String language = 'Dart'; // explicit type is also fine

  // name = 'Grace';  // error: a final variable can only be set once

  final now = DateTime.now();     // not known until the program runs
  print('$name uses $language at $now');
}

Use final for anything that should not change after it is set. Most of the local variables in well-written Dart are final, which makes code easier to follow: when you see final, you know the name always refers to the same thing.

A final variable can be a class field too, and it may be initialized later (in a constructor), as long as it is set once. You will see that in the lesson on constructors.

const: known before the program runs

const is stricter. A const variable is a compile-time constant: its value must be fully determined by the compiler, from literals and other constants. No function calls that run at runtime, no DateTime.now().

DART
const pi2 = 3.14159 * 2;          // fine: arithmetic on literals
const appName = 'Notes';
const maxItems = 100;
const greeting = 'Welcome to $appName';   // interpolation of constants is allowed

// const now = DateTime.now();    // error: not a compile-time constant

What does that buy you? Constants cost nothing at runtime, they can be shared, and Dart can canonicalize them, meaning two identical const objects are the very same object in memory.

DART
void main() {
  var a = const [1, 2, 3];
  var b = const [1, 2, 3];
  print(identical(a, b));   // true: one shared object
}

final versus const

The two are easy to mix up, so here is the rule:

final const
Can be reassigned No No
Value known At runtime, when first assigned At compile time
Can call normal functions Yes No
Makes the object itself immutable No Yes

That last row is the surprising one. A final list cannot be replaced by another list, but you can still change its contents. A const list is frozen all the way down:

DART
void main() {
  final fruits = ['apple', 'pear'];
  fruits.add('plum');              // fine: the list is mutable
  print(fruits);                   // [apple, pear, plum]
  // fruits = ['kiwi'];            // error: final variable

  const colors = ['red', 'green'];
  // colors.add('blue');           // throws at runtime: unsupported operation
}
flowchart LR
    A["Do you know the value<br/>when you write the code?"] -->|"Yes, and it never changes"| B["const"]
    A -->|"No, but it won't change<br/>after being set"| C["final"]
    A -->|"It changes as the<br/>program runs"| D["var or an explicit type"]

Choosing a declaration. Start with final, and use var only when the variable really needs a new value.

The word const also appears before a constructor call or a collection literal, as in const [1, 2, 3] above. In a const declaration the inner const is optional because the context is already constant.

TypeScript final versus const, approximated in TypeScript (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The table matters because the names in TypeScript and JavaScript mean something different: their const corresponds to Dart's final, not to Dart's const.

Constants are canonicalized: equal const values are one shared object in memory. That is why identical(const [1, 2], const [1, 2]) is true, and it is why a const collection cannot be changed afterwards. Reassigning a final or const variable is a compile-time error, but a final variable can still hold an object that changes internally (a final list can have items added; a const one cannot).

A first look at late

Sometimes a non-nullable variable cannot be initialized on the line where it is declared, but you know you will set it before reading it. The late modifier tells Dart to trust you and check at runtime:

DART
late String greeting;

void main() {
  greeting = 'Hello';
  print(greeting);
}

If you read a late variable before it has a value, Dart throws a LateInitializationError. late can also delay expensive work: a late final variable with an initializer only runs it the first time the variable is used. The full story is in the lesson on late variables.

Naming rules

Variable names in Dart use lowerCamelCase: userName, maxRetries. They may contain letters, digits, underscores and $, cannot start with a digit and cannot be a reserved word such as class or if. Constants also use lowerCamelCase in modern Dart (maxItems), not SCREAMING_CAPS. A name starting with an underscore, _count, is private to its library, which you will meet in the lessons on classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After var count = 5;, which assignment is a compile-time error?

    var infers the type int from the initial value, so the variable stays an int. Assigning a String to it is an error.
  2. 2. Which declaration is a compile error?

    A const must be known at compile time. DateTime.now() is only known when the program runs, so use final instead.
  3. 3. final items = ['a']; followed by items.add('b'); does what?

    final stops you from pointing the variable at another list, but the list itself is still mutable. A const list would reject add.
  4. 4. What happens if you read a late variable that has not been assigned?

    late moves the check from compile time to runtime. Reading too early throws a LateInitializationError.

Summary

  • var infers a type from the value; the type is then fixed. Write an explicit type when it helps readability, especially in public APIs.
  • final allows exactly one assignment, and the value may be computed at runtime.
  • const is a compile-time constant and makes the object deeply immutable; identical constants are shared.
  • An uninitialized variable is null only when its type ends with ?.
  • late delays initialization, with a runtime check.

Next, explore the two number types in Numbers: int and double.