Lesson 3 / 25

Variables, final, const and Basic Types

Declare variables with var, final, const and late, and use Dart's core types.

Values and types

Declare variables with var (type inferred, reassignable), an explicit type (int count = 0), final (assigned once, at run time) or const (a compile-time constant, deeply immutable). Prefer final for values that do not change, and const for values known at compile time, which Dart canonicalises: identical const objects share one instance, an important optimisation for Flutter widgets. Everything is an object, including numbers and functions, and every type is a subtype of Object?. Core types: int and double (both num), String (UTF-16, with interpolation '$name' and '${expr}', and multi-line triple quotes), bool, List, Set, Map, Record, Function and Null. dynamic turns off static checking for a value and should be rare; Object? is the safe way to say "anything". Dart has no implicit conversions between int and String: use int.parse, int.tryParse and toString(). late declares a non-nullable variable that will be initialised before use, checked at run time.

var, final, const and conversions

const values are compile-time constants; final values are set once at run time.

void main() {
  var quantity = 3;                 // int, reassignable
  final createdAt = DateTime.now();  // set once at run time
  const gstRate = 0.18;              // compile-time constant
  const sizes = ['S', 'M', 'L'];     // deeply immutable const list

  final unitPrice = 49.5;
  final total = quantity * unitPrice * (1 + gstRate);
  print('Total: ${total.toStringAsFixed(2)}');

  final parsed = int.tryParse('42') ?? 0;   // null if the text is not a number
  final label = 'Qty: ' + quantity.toString();

  // sizes.add('XL');                // runtime error: cannot modify a const list
  // createdAt = DateTime.now();     // compile error: final cannot be reassigned

  print(identical(const [1, 2], const [1, 2]));   // true: canonicalised
}

final versus const

final means "this variable is assigned once"; the object may still be mutable (a final List can be added to). const means the value itself is a compile-time constant and deeply immutable. Use const wherever possible in Flutter widget trees.

Quick check: What is the difference between final and const in Dart?

  • There is none
  • const can be reassigned
  • final is set once at run time; const must be a compile-time constant and is deeply immutable
  • final only works with numbers
Answer

final is set once at run time; const must be a compile-time constant and is deeply immutable — const values are known at compile time and canonicalised; final variables are assigned once.