Variables, types, final and const

Dart · Essentials · 10 min

Every Dart program and Flutter widget starts with these declarations, and final vs const matters for performance.

A Dart program starts at void main(). Statements end with semicolons, and print writes a line.

Declare variables with:

  • var name = 'Dart'; — type inferred (String) and fixed; you can reassign another String.
  • An explicit type: int count = 0;.
  • final — assigned once, at run time: final now = DateTime.now();.
  • const — a compile-time constant: const maxItems = 100;. Const values are canonicalized, so two identical const objects are the same instance; Flutter uses this to skip rebuilding const widgets.

Core types: int, double (both subtypes of num), String, bool, plus List, Set, Map, Record and Object. Everything, including numbers and null, is an object. Conversion is explicit: int.parse('42'), 3.7.toInt(), n.toString().

Strings use single or double quotes; interpolate with $name or ${expr}. Triple quotes make multi-line strings, and r'...' is a raw string.

dynamic turns off static checking for a variable — avoid it; use Object? when you truly accept anything.

Dart is statically and soundly typed: if a variable's static type is int, it really holds an int at run time. The type checker catches most mistakes before you run.

Example

void main() {
  var language = 'Dart';      // String, inferred
  int year = 2011;
  final launched = DateTime(year);
  const maxScore = 100;

  year += 14;
  print('$language turns ${year - launched.year}');  // Dart turns 14

  double ratio = 7 / 2;       // / always gives a double
  int whole = 7 ~/ 2;         // integer division
  print('$ratio $whole');     // 3.5 3

  print(int.parse('42') + maxScore);   // 142
  const a = [1, 2];
  const b = [1, 2];
  print(identical(a, b));     // true: const values are canonical
}

Remember

  • var infers, final is set once, const is a compile-time constant
  • / returns double; ~/ is integer division
  • Interpolate with $x and ${expr}

Watch out for

  • Using dynamic to silence type errors, which moves them to run time.

Check yourself

  1. What is the difference between `final` and `const`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: dart.dev/language/variables