Sub topic 2
Variables, final, const, and built-in types
This chapter assumes you can program in another typed language and can run a Dart file with dart run. It covers how Dart declares variables, how final and const differ, and how the core built-in types behave.
Declaring variables
Dart is statically typed, but you usually don't need to write the type. When you use var, the compiler infers the type from the initializer and fixes it for the life of the variable.
void main() {
var count = 1; // inferred as int
count = 2;
// count = 'two'; // compile-time error: String is not an int
String title = 'Dart'; // explicit type
final created = DateTime.now(); // inferred, assigned once
const maxItems = 10; // compile-time constant
print('$count $title $maxItems ${created.year > 2000}');
}Use var for local variables where the type is obvious. Write the type explicitly on public APIs, such as fields, parameters, and return types, because the type is part of the contract.
Inference gotchas
Inference depends entirely on the initializer. Two cases catch people out:
var x;has no initializer, so x isdynamicand the compiler stops checking it.var items = [];is aList<dynamic>. Write<int>[]orList<int> items = []to get a typed list.
dynamic, Object, and Object?
These three look similar but behave differently.
void main() {
dynamic a = 'text';
print(a.length); // allowed: checked only at runtime
a = 5;
// a.length now throws NoSuchMethodError at runtime
Object b = 'text';
// b.length is a compile-time error: Object has no length
if (b is String) {
print(b.length); // b is promoted to String here
}
}dynamicturns off static checking. A mistake becomes a runtime exception.Objectis the root of all non-nullable types. You can only call members thatObjectdefines until you check the type.Object?is the root of every type, includingnull.
After an is check, Dart promotes a local variable to the narrower type inside the guarded branch. Promotion works for local variables and parameters. It does not work for mutable fields, because another piece of code could change the field between the check and the use.
final and const
Both keywords make a variable single-assignment. They differ in when the value is known.
finalmeans the variable is assigned once, and the value can be computed at runtime.constmeans the value is a compile-time constant. The compiler must be able to compute it before the program runs.
void main() {
final now = DateTime.now(); // runtime value: fine for final
// const bad = DateTime.now(); // error: not a constant expression
const limit = 100;
const doubled = limit * 2; // constant arithmetic is allowed
print('$limit $doubled ${now.year > 2000}');
}Shallow versus deep immutability
A final variable cannot be reassigned, but the object it points to can still change. A const collection is immutable all the way down.
void main() {
final growable = [1, 2];
growable.add(3); // fine: the list is mutable
// growable = [9]; // error: the variable is final
const fixed = [1, 2];
try {
fixed.add(3);
} on UnsupportedError catch (e) {
print('const list rejected add: ${e.runtimeType}');
}
print(identical(const [1, 2], const [1, 2])); // true
print(growable);
}Constant objects are canonicalized. Two const expressions with the same values produce one shared instance, which is why identical returns true. This saves memory, and Flutter relies on it to skip rebuilding unchanged widgets.
You can also use const as a modifier on a literal inside a non-const context, as in final list = const [1, 2];. The variable is final, and the list it holds is constant.
late variables
The late modifier delays initialization. It has two uses: a non-nullable variable that you will assign before first use, and a lazily computed value.
String _load() {
print('loading');
return 'config';
}
late final String config = _load();
void main() {
print('start');
print(config); // _load runs here, on first read
print(config); // cached: no second "loading"
}The output is start, loading, config, config. If you read a late variable that was never assigned and has no initializer, Dart throws a LateInitializationError at runtime. Treat late as a promise to the compiler that you must keep.
Choosing a keyword
| Keyword | Assigned | Value known | Typical use |
|---|---|---|---|
| `var` | Many times | Runtime | Loop counters, accumulators |
| `final` | Once | Runtime | Most local values and fields |
| `const` | Once | Compile time | Fixed numbers, strings, constant objects |
| `late` | Once or lazily | First use | Expensive or dependent initialization |
The Dart style guide recommends final by default and var only when you need to reassign.
Numbers
Dart has two concrete number types, int and double, and a common supertype, num.
void main() {
int a = 7;
double b = 2; // an int literal is accepted and becomes 2.0
print(a / 2); // 3.5: "/" always returns a double
print(a ~/ 2); // 3: truncating integer division
print(a % 2); // 1
print(-7 % 3); // 2: the result of % is never negative
print(-7 ~/ 2); // -3: truncates toward zero
print(b); // 2.0
num n = 3;
n = 3.5; // num holds either kind
print(n);
print(int.parse('42') + 1);
print(double.tryParse('x')); // null instead of an exception
print(3.7.round()); // 4
print(3.7.toInt()); // 3
print(0.1 + 0.2); // 0.30000000000000004
}Points to remember:
/always yields adouble, even forintoperands. Use~/when you want an integer.- Dart does not convert a
doubleto anintimplicitly. Call.toInt(),.round(),.floor(), or.ceil(). int.parsethrows aFormatExceptionon bad input.int.tryParsereturnsnull.- On the Dart VM,
intis a 64-bit signed integer. When compiled to JavaScript for the web, numbers are JavaScript doubles, so integers are exact only up to 2^53. Code that depends on 64-bit overflow behavior will differ between platforms. doublefollows IEEE 754, so0.1 + 0.2is not exactly0.3. Compare with a tolerance, and don't use doubles for money.
Strings, booleans, and null
A String is an immutable sequence of UTF-16 code units. Single and double quotes are equivalent, and $name interpolation is covered in the next chapter.
A bool is exactly true or false. Dart has no truthiness. if (1), if (''), and if (list) are compile-time errors, so write list.isNotEmpty or count != 0.
null is the only value of type Null. A variable can hold it only if its type ends in ?, as in int?. The chapter on null safety covers this.
Checking types at runtime
The is and is! operators test a type. The runtimeType property reports the actual type of an object, which is useful for debugging but a poor basis for logic.
void main() {
Object value = 42;
print(value is int); // true
print(value is num); // true: int is a subtype of num
print(value is! String); // true
print(value.runtimeType); // int
}Common errors
- Reassigning a
finalorconstvariable. The analyzer reports it before you run the code. - Using
constwith a runtime value, such asconst t = DateTime.now();. Change it tofinal. - Mutating a
constcollection. The analyzer will not catch this in every case, and it fails at runtime withUnsupportedError. - Writing
var x;and losing type checking. Give it a type or an initializer. - Assigning the result of
/to anint. Use~/or convert the result.
Exercise
Given final a = [1, 2]; and const b = [1, 2];, which of a.add(3) and b.add(3) succeeds, and what happens with the other?
Show answer
a.add(3) succeeds, because final only stops reassignment of the variable and the list stays mutable. b.add(3) throws an UnsupportedError at runtime, because a const list is immutable.
Exercise
What are the values of 9 / 2, 9 ~/ 2, and -9 % 4 in Dart?
Show answer
9 / 2 is 4.5 (always a double), 9 ~/ 2 is 4 (truncating division), and -9 % 4 is 3 (the remainder of % is never negative).