Skip to content
AgileLogics
5 min read

Variables: var, final, and const

Prerequisites: Printing output

A variable gives a name to a value so you can use it later.

Real-world analogy: a variable is a labeled box. A var box can be refilled; a final box is sealed once filled; a const box was sealed at the factory, before the program even ran.

Syntax

var score = 0;          // can be reassigned
final city = 'Lagos';   // set once
const maxPlayers = 4;   // fixed when the program is compiled

Example

void main() {
  final city = 'Lagos';
  var temperature = 24;

  print(city);
  print(temperature);

  temperature = 27;
  print(temperature);

  temperature += 1;
  print(temperature);
}

Expected output

Lagos
24
27
28

temperature += 1 is short for temperature = temperature + 1. Dart also has temperature++.

final vs const

  • final — assigned once, but the value can be worked out while the program runs: final now = DateTime.now();.
  • const — the value must be known when the program is compiled: literals and calculations on them. const values are created once and shared, which Flutter uses heavily for performance.

Prefer final for anything that doesn't change, and var only when it must. The analyzer's recommended lints nudge you toward this.

Common mistakes

  • Reassigning a final variable:
void main() {
  final limit = 10;
  limit = 20;
}
hello.dart:3:3: Error: Can't assign to the final variable 'limit'.
  • Using const for a value only known at runtime: const now = DateTime.now(); is an error — use final.

Practice

Create a final appName and a var launchCount starting at 0. Increase launchCount twice, then print Notes has launched 2 times.

Hint: put a variable inside a string with $: '$appName has launched ...'.

Show solution
void main() {
  final appName = 'Notes';
  var launchCount = 0;
  launchCount++;
  launchCount++;
  print('$appName has launched $launchCount times');
}
Notes has launched 2 times