Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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

The shortcut

Ask two questions in order, and stop at the first yes.

Declaring Sprout's watering intervalStep 1 of 4
  1. Is the value written in the source and never changes?

    The default interval of 7 days is. Use const defaultDays = 7;

Prefer final over var when in doubt. Most values in a Flutter app never change after they are created, and final makes accidental reassignment impossible.

Drills

Answer fast — trust the rule.

quick drill

What happens with var count = 3; count = 'three';?

quick drill

Which declaration is an error?

quick drill

What is the value of int? days; before anything is assigned?

quick drill

A plant's name is loaded from storage and must never change afterwards. Best declaration?

Remember

  • var may change, final is set once, const is fixed before running.
  • Ask: written in source? const. Set once? final. Otherwise var. Might be missing? add ?.
  • Trap: const with a run-time value, and assigning null to a type without ?.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainPick the right keyword

Sprout stores three values: the app's name, the moment the app was opened, and a plant's last watering date that may not be known yet. Declare each one with the best keyword and type, and explain your choice for each.