Skip to the workspace
Pebellslearn by building
Basics of Dart  ›  Lesson

Variables: var, final and const

Variables 12 minDart variables are declared with var, a type, final or const, and null safety means a type only allows null when it ends with a question mark.

flutter / Variables: var, final and const

Explore each scene at your own pace.

01 · The rule

The rule

Variables: var, final and const

Sprout needs to remember things: the app's name, how many plants you own, when the fern was last watered. Dart gives you four ways to declare a variable, and choosing well tells the next reader, and the compiler, how that value is allowed to behave.

The rule

var may change, final is set once, const is fixed before running.

var plantCount = 3;           // can be reassigned
final openedAt = DateTime.now(); // assigned once, at run time
const appName = 'Sprout';     // known when the code is compiled
String nickname = 'Fernie';   // explicit type, can be reassigned
  • var lets Dart infer the type from the first value. plantCount is an int forever, so plantCount = 'three'; is an error, while plantCount = 4; is fine.
  • final can never be reassigned, but its value may come from a calculation at run time.
  • const is stricter: the value must be computable by the compiler. const openedAt = DateTime.now(); fails, because the time only exists once the app runs.

Null safety adds one more rule. A plain String can never hold null. Add ? to allow it:

DateTime? lastWatered;   // starts as null, allowed
int days = null;         // error: int does not accept null
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.