Thuta Learning
Dart
BasicProgrammingBeginner

Variables

DartLesson 530 min

What you'll walk away with

  • Choose between var, an explicit type, final, const and late for a given situation
  • Explain why final can hold a run-time value but const needs a compile-time constant
  • Predict the compile error for assigning the wrong type to a variable or a second value to a final
  • Recognize that var without an initializer becomes dynamic, and why that matters
  • Explain that String.length counts UTF-16 code units, using Myanmar text and an emoji

Explain it simply

Variables, simply

A variable is a labelled box: the label is the name and what sits inside is the value. Dart adds two rules to every box. The first is that the box has a fixed kind of content, its type: a box for whole numbers will not accept text. The second is that you choose how freely the box can change: var accepts new values, final accepts exactly one, and const is filled while the program is still being compiled.

Most variables in good Dart code are final. Once a value is set a single time, nothing later in the code can change it unexpectedly.

Problem → Why → Solution

The problem: three misuses of a box at once

A first attempt at a few variables often goes wrong in three ways at once. The first line gives a count a text value, as if var meant 'any type'. The second reassigns a final variable. The third tries to build a constant from the current time. Dart reports all three and refuses to run, though not in line order: variables.dart:3:11: Error: A value of type 'String' can't be assigned to a variable of type 'int'. and variables.dart:6:3: Error: Can't assign to the final variable 'name'. and variables.dart:8:26: Error: Cannot invoke a non-'const' constructor where a const expression is expected.

In JavaScript each of those lines would either work or fail only when run. Dart insists that you decide, at the moment of declaration, what type a variable holds, whether it may change, and when its value becomes known.

variables.dart
void main() {
  var count = 0;
  count = 'zero';

  final name = 'Aye';
  name = 'Ko';

  const today = DateTime.now();
}

Why there are different keywords

Each keyword is a promise to the compiler and to the next reader. var promises a type that stays fixed, final promises a value that is set once, and const promises a value known before the program runs. Because the compiler enforces the promises, a variable you read three screens later behaves the way its declaration says.

Core concept: a name, a type and an assignment rule

Declaring a variable means choosing three things: a name, a type and an assignment rule. The type is either written by you (String framework = 'Flutter';) or inferred by Dart from the first value (var language = 'Dart'; makes language a String). In both cases the type is fixed from that moment: assigning a value of another type later is a compile error, which was the first problem in this lesson. That is the biggest difference between Dart's var and JavaScript's var or let.

KeywordRuleTypical use
var or Type nameCan be reassigned any number of times, with the same typeCounters and values that keep changing
finalAssigned exactly once, while the program runsA value worked out at run time and never changed, such as a result or a timestamp
constAssigned once, with a value known at compile timeFixed numbers and text, such as a tax rate or a maximum score
lateDeclared now, assigned before it is first readA value that depends on something not ready yet, or an expensive value computed on first use

final and const both forbid reassignment, but they ask for different things. A final variable gets its value while the program runs, so it may use any expression, such as language.toUpperCase() or DateTime.now(). A const variable must be built entirely from values the compiler already knows, which rules out calls like DateTime.now(). In return, a const value is created once at compile time and shared.

late tells Dart: trust me, this variable will have a value before anyone reads it. If you break that promise you get a LateInitializationError at run time instead of a compile error. A late variable with an initializer is computed only when it is first read, so it can postpone expensive work.

In Dart 3 a variable cannot hold null unless its type ends in ?. And var without an initializer (var x;) has no value to infer a type from, so Dart makes it dynamic, which switches type checking off for that variable; avoid that form.

Mental model: a labelled box with rules
  1. Name the box and fix its type
  2. Choose how often it can be assigned
  3. Dart rejects wrong types and re-assigns

Ask two questions for every variable: will its value change, and is it known before the program runs? The answers pick var, final or const.

General pattern: five ways to declare

dart
var name = value;          // type inferred from value
Type name = value;         // explicit type
final name = value;        // assigned once, at run time
const name = value;        // compile-time constant
late Type name;            // assigned later, before first use

The first two lines are variables whose value can change: one with an inferred type and one with a written type. The last three restrict reassignment. final and late can also be written with a type (final String name = value;) and combined as late final.

Example: the five declarations side by side

Each declaration style appears once in this program. Notice that shout is calculated before language changes, so it stays DART even though language later becomes Dart 3. Write down the three output lines before you run it.

variables.dart
void main() {
  var language = 'Dart'; // inferred as String
  String framework = 'Flutter'; // explicit type
  final shout = language.toUpperCase(); // fixed at run time
  const maxScore = 100; // known while compiling
  late final String report; // assigned later, exactly once

  language = 'Dart 3'; // allowed: var can be reassigned
  report = '$language + $framework, max $maxScore';

  print(report);
  print('Shout: $shout');
  print(language.runtimeType);
}

Code breakdown

  1. An inferred variablevar language = 'Dart';

    Dart infers String for language from 'Dart'. Because of var it can be changed later, but its type stays String.

  2. A written typeString framework = 'Flutter';

    The result is the same as above; only the type is spelled out. In places other people will read, such as fields and function signatures, this form is easier to read.

  3. A final value from run timefinal shout = language.toUpperCase();

    toUpperCase() is called while the program runs, so const is not allowed and final is used. The value is set once and stays 'DART'.

  4. A compile-time constantconst maxScore = 100;

    100 is an integer the compiler already knows, so const is fine. No type is written, but it is inferred as int.

  5. A late final variablelate final String report;

    report is declared now and assigned exactly once later. Reading it before the assignment is caught by the compiler for a local variable like this one.

  6. Reassigning a varlanguage = 'Dart 3';

    Allowed, because language is a var and the new value is a String, so the type is right. language = 3 would be a compile error. Note that shout does not change.

  7. Using the late variablereport = '$language + $framework, max $maxScore';

    This is the first and only assignment to the late final variable. The $ markers insert the values of all three variables into the text. A second assignment would be an error.

You should see
Dart 3 + Flutter, max 100
Shout: DART
String

final and const with collections

final locks the variable, not what is inside it. You can add to a final list; what you cannot do is point scores at a different list. A const list is a list that can never change at all: adding to it throws Unsupported operation: Cannot add to an unmodifiable list at run time. Equal const values are one single object, which is why identical returns true.

collections.dart
void main() {
  final scores = [80, 90];
  scores.add(100); // allowed: the list changes, the variable does not
  print(scores);

  const days = ['Mon', 'Tue'];
  print(days.length);
  print(identical(days, const ['Mon', 'Tue']));
}

Running it prints [80, 90, 100], 2 and true.

Type inference, dynamic and Object

With no initializer, var loose; makes Dart treat loose as dynamic, so both loose = 1; and loose = 'now text'; are accepted. runtimeType reports the type of the actual value, so it ends up as String and never says dynamic. Object can hold any value too, but you may only use members that Object itself has.

dynamic_object.dart
void main() {
  var loose; // no initializer: the type is dynamic
  loose = 1;
  loose = 'now text';
  print(loose.runtimeType);

  Object anything = 42; // any value, but only Object's own members
  print(anything.runtimeType);
  print(anything is int);
}

The difference is when the mistake is caught. Calling .isEven on a dynamic that holds a String fails at run time with NoSuchMethodError: Class 'String' has no instance getter 'isEven'. Calling .isEven on an Object is stopped by the compiler before running: The getter 'isEven' isn't defined for the type 'Object'. Catching a mistake at compile time is always better.

Numbers and strings as variables

In Dart a whole number is an int, a fractional number is a double, and num can hold either. double ratio = 7 / 2; gives 3.5, because / always returns a double. A String is a sequence of UTF-16 code units, and length counts code units, not the characters your eye sees. The Myanmar word ကျောင်း is written with 7 code points, so its length is 7; the emoji 😀 needs two code units, so its length is 2, while runes counts a single code point and gives 1. The Data Types lesson goes deeper.

numbers_text.dart
void main() {
  int whole = 7;
  double ratio = 7 / 2; // / always gives a double
  num either = whole;
  either = 3.5;
  print('$whole $ratio $either');

  var burmese = 'ကျောင်း'; // the word for school
  var smile = '😀';
  print(burmese.length);
  print(smile.length);
  print(smile.runes.length);
}

In real projects

Choosing variable kinds in real projects

In real projects const is for values that never change across the whole app: padding sizes, an API path, a maximum number of retries. final is for values that are only known at run time: the time a request arrived, the id of the logged-in user, the result of a calculation. In Flutter, late is common for objects such as controllers that are created inside initState.

Lint rules such as prefer_final_locals and prefer_const_declarations nudge you to make a variable final or const whenever it never needs to change. In Flutter, const widgets also help the framework skip rebuilding identical subtrees. These habits let a reader learn from the declaration alone whether a value can change.

Common mistakes

Common variable mistakes

1. Putting a run-time value into a const

const today = DateTime.now(); gives Cannot invoke a non-'const' constructor where a const expression is expected., because the clock is read only when the program runs. Write final today = DateTime.now(); instead. const is only for values that are known at compile time.

2. Using var without an initializer

With var price; the variable is dynamic, so price = 'free'; and price = 3.5; both compile, and the compiler no longer checks price + 1 either. Mistakes appear only at run time. Fix the type with double price = 0; or var price = 0.0;.

3. Reading a late variable before assigning it

Reading a late top-level variable or field before load() has assigned it throws LateInitializationError: Field 'config' has not been initialized. at run time. For a local variable inside a function, the compiler warns earlier: Late variable 'config' without initializer is definitely unassigned. Treat late as a promise you have made.

4. Assuming final means the contents cannot change

final names = ['Aye']; followed by names.add('Ko'); works, because final locks only the variable. If you want a list that can never change, use const, and remember that adding to it then fails with a run-time error.

Best practices

Best practices

  • Make every local variable final unless it must be reassigned, and use var only for that case.
  • Make fixed numbers and text const, and give them names that explain why the value is what it is.
  • Write types on public places such as fields and function signatures, and trust the inference of var and final for locals.
  • Avoid dynamic, and keep it for the rare case where the type genuinely cannot be known.

Mini challenge

Mini challenge: an order summary

Write a program that works out an order for an online shop: each item costs 15000 kyat, tax is 5 percent and shipping is 2000 kyat. Declare every value with the keyword that suits it.

  • Declare taxPercent (5) and shipping (2000) with const
  • Declare itemCount with var, starting at 2, then add one more item
  • Work out subtotal, tax (integer percentage) and total with final
  • Assign a late final String summary once the numbers are known, then print the summary and the total
order.dart
void main() {
  // TODO: const taxPercent = 5 and const shipping = 2000
  // TODO: var itemCount that starts at 2, then increase it by one
  // TODO: final subtotal (15000 per item), final tax and final total
  // TODO: late final String summary, assigned after the numbers are known
  // TODO: print the summary, then the total followed by MMK
}

Expected: The program prints these two lines: Items: 3, subtotal: 45000, tax: 2250, shipping: 2000 Total: 49250 MMK

Show hint

Work out tax with subtotal * taxPercent ~/ 100 (~/ is integer division). Build summary with interpolation such as 'Items: $itemCount, subtotal: $subtotal ...', and if it gets long, split it over two lines with two adjacent string literals.

Show solution
order.dart
void main() {
  const taxPercent = 5;
  const shipping = 2000;
  var itemCount = 2;
  itemCount = itemCount + 1;

  final subtotal = itemCount * 15000;
  final tax = subtotal * taxPercent ~/ 100;
  final total = subtotal + tax + shipping;

  late final String summary;
  summary = 'Items: $itemCount, subtotal: $subtotal, tax: $tax, '
      'shipping: $shipping';
  print(summary);
  print('Total: $total MMK');
}

Quick quiz 1 / 3

Why does Dart reject const now = DateTime.now();?

Quick quiz 2 / 3

What does var x; x = 1; x = 'a'; print(x.runtimeType); print?

Quick quiz 3 / 3

What does final names = ['Aye']; names.add('Ko'); print(names); print?

What to remember

  • var and a written type give variables that can change, and a type never changes once it is set
  • final is assigned once at run time, const must be a compile-time constant, and late must be assigned before its first read
  • var without an initializer is dynamic and turns type checking off, so avoid it
  • A final list can be added to but a const list cannot, and String.length counts UTF-16 code units

Dart language overview — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Variables | Thuta Learning