A type system you can trust
Every value in Dart has a type, and every variable has a declared or inferred static type that the compiler checks before the program runs. Dart's type system is sound: if the analyzer says an expression has type String, then at run time it will be a String, never something else in disguise. That is a stronger promise than TypeScript's or Python's type hints make, and it lets the compilers generate faster code.
The most valuable part of that promise is about null. Before 2021, any Dart variable could hold null, and forgetting to check was the most common crash in Dart and Flutter apps, as it is in Java and JavaScript. Dart 2.12 introduced sound null safety, and Dart 3 made it mandatory: a variable of type String can never be null. If a value might be missing, its type says so, with a question mark: String?. The compiler then insists that you deal with the missing case before using the value.
This lesson covers how to declare variables, the everyday types, and the small set of operators that make nullable values pleasant to work with.
var, final, const and late
Definition— var, final, const
var declares a variable whose value can change; its type is inferred from the initial value. final declares a variable that is assigned exactly once. const declares a compile-time constant: its value must be computable by the compiler, it is deeply immutable, and identical constants share one object in memory.
var visitors = 0; // an int that can change
final today = DateTime.now(); // assigned once, at run time
const pi = 3.14159; // known when the program is compiled
String label = 'Total'; // an explicit type instead of varAssigning to a final variable a second time fails with Can't assign to the final variable 'f'. (for a variable named f). The difference between final and const is when the value is known. DateTime.now() can be final but not const, because nobody knows the time until the program runs. A const list, map or object is frozen all the way down, while a final list is a variable that always refers to the same list, whose contents you can still change. Effective Dart asks only that a codebase follow one consistent rule for var versus final on local variables; many teams use final for everything that is not reassigned and const wherever a value is truly constant, and enable lints such as prefer_final_locals and prefer_const_constructors to suggest them automatically.
A late variable is non-nullable but initialized after its declaration. The compiler trusts you, and checks at run time instead: reading it before it has a value throws a LateInitializationError. Use late sparingly, for values set up just after construction or computed lazily (late final x = expensive(); runs expensive only on first use).
Type annotations are optional for local variables; Effective Dart recommends letting inference work there and annotating public APIs: function parameters, return types and fields. Two types deserve a warning. Object? is the top of the type hierarchy: anything can be stored in it, but you must check or cast before using it as something specific. dynamic turns type checking off: any method call compiles and fails only at run time if the method does not exist. Avoid dynamic except at the edges where you parse untyped data such as JSON, and even there, convert to real types quickly.
Numbers
Dart has two number types, int and double, both subtypes of num. On native platforms an int is a 64-bit integer; on the web, compiled to JavaScript, integers are JavaScript numbers and are exact only up to 2 to the power 53, one of the few places where Dart's behaviour depends on the platform.
void main() {
var count = 10; // inferred as int; can change
final price = 2.5; // inferred as double; assigned once
const maxUsers =
1_000; // a compile-time constant (digit separators: Dart 3.6)
count += 5;
print('$count ${count * price} $maxUsers');
print(7 / 2); // / always gives a double
print(7 ~/ 2); // ~/ divides and truncates toward zero
print(-7 ~/ 2);
print(-7 % 2); // % is never negative for a positive divisor
print((-7).remainder(2)); // remainder() keeps the sign of the dividend
print(int.parse('42') + 1);
print(int.tryParse('forty-two')); // null instead of an exception
print(double.parse('3.75').round());
print('${10.toDouble()} ${3.99.toInt()}');
const big = 9223372036854775807; // the largest 64-bit int
print(big + 1); // native ints wrap around silently
print(0.1 + 0.2);
print('${1e3} ${2.0 * 3}');
}15 37.5 1000
3.5
3
-3
1
-1
43
null
4
10.0 3
-9223372036854775808
0.30000000000000004
1000.0 6.0- Division.
/always produces adouble, even for7 / 2. For integer division use~/, which truncates toward zero:-7 ~/ 2is −3. - Remainder. Dart's
%is the Euclidean modulo: for a positive divisor the result is never negative, so-7 % 2is 1, which is exactly what you want for wrapping around a clock or a circular buffer. If you want the remainder with the sign of the dividend, as in C or Java, callremainder. (Write(-7).remainder(2)with parentheses: in-7.remainder(2)the method call happens first and the minus sign afterwards.) - Parsing.
int.parsethrows aFormatExceptionon bad input;int.tryParsereturnsnullinstead, which is usually what you want for user input. - No implicit conversions between variables. An integer literal can be used where a
doubleis expected (double d = 3;is fine), but anintvariable cannot:double d = i;fails withA value of type 'int' can't be assigned to a variable of type 'double'.Convert withtoDouble(),toInt()(truncates), orround(). - Overflow wraps. On native platforms,
intarithmetic silently wraps around at 64 bits, so the largestintplus one is the most negative one. Unlike Swift, Dart does not trap. For arbitrarily large integers, useBigInt. - Floating point behaves as everywhere else:
0.1 + 0.2is not exactly 0.3. Use integers of cents for money.
Underscores in number literals (1_000) are allowed since Dart 3.6, purely for readability.
Strings
A String is an immutable sequence of UTF-16 code units. You never change a string; operations return new ones.
void main() {
final city = 'Kraków';
print(city.toUpperCase());
print(city.substring(0, 3));
print(city.contains('ków'));
print(
'Kraków' ==
'Krak'
'ów',
); // adjacent literals are joined
final parts = 'Lima;Quito;La Paz'.split(';');
print('${parts.length} ${parts.last}');
print('7'.padLeft(3, '0'));
final path = r'C:\new\folder'; // a raw string: backslashes are literal
print(path);
const poem = '''
Rain on the tin roof,
the kettle answers.''';
print(poem);
// Strings are immutable; build big ones with a StringBuffer.
final buffer = StringBuffer();
for (var i = 1; i <= 3; i++) {
buffer.write('step $i; ');
}
print(buffer.toString().trim());
}KRAKÓW
Kra
true
true
3 La Paz
007
C:\new\folder
Rain on the tin roof,
the kettle answers.
step 1; step 2; step 3;Most methods are what you would guess: toUpperCase, substring (start inclusive, end exclusive), contains, split, padLeft, trim. Strings compare with == by content. Two string literals written next to each other are joined at compile time, which is handy for breaking a long literal across lines. An r prefix makes a raw string, in which backslashes and dollar signs are ordinary characters, useful for Windows paths and regular expressions. Triple quotes make a multi-line string that keeps its line breaks and indentation exactly as written.
Because strings are immutable, building one with += in a loop creates a new string each time. A StringBuffer collects the pieces and joins them once at the end, which matters when the loop runs thousands of times.
Sound null safety
Definition— nullable type
For every type T, the type T? contains all the values of T plus null. A non-nullable type such as String or int can never hold null; the compiler rejects any code that might put null there, and any code that uses a T? as if it were a T.
Try String name = null; and the compiler answers A value of type 'Null' can't be assigned to a variable of type 'String'. Try to call .length on a String? and it answers Property 'length' cannot be accessed on 'String?' because it is potentially null. To get from String? to String, you use one of a few tools:
int? findIndex(List<String> names, String wanted) {
for (var i = 0; i < names.length; i++) {
if (names[i] == wanted) return i;
}
return null;
}
String? nicknameOf(String name) => name == 'Bruno' ? 'Bru' : null;
void main() {
final names = ['Adaeze', 'Bruno', 'Chiara'];
int? where = findIndex(names, 'Bruno');
int? missing = findIndex(names, 'Dmitri');
print('$where $missing');
// ?? supplies a default; ?. calls a method only if the value is not null.
print(missing ?? -1);
String? nick = nicknameOf('Chiara');
print(nick?.toUpperCase());
print(nick?.length ?? 0);
// ??= assigns only if the variable is still null.
nick ??= 'Chi';
print(nick);
// Flow analysis: after the check, `where` is promoted to a non-null int.
if (where != null) {
print('Found at ${where + 1}');
}
// ! asserts that a value is not null (and throws if it is).
final first = int.tryParse('12')!;
print(first * 2);
// late: a non-nullable variable initialized later, checked at run time.
late final String greeting;
final hour = DateTime(2026, 1, 1, 9).hour;
greeting = hour < 12 ? 'Good morning' : 'Good afternoon';
print(greeting);
}1 null
-1
null
0
Chi
Found at 2
24
Good morning?.(null-aware access) calls the method only if the receiver is notnull; otherwise the whole expression isnull. Its result is therefore nullable.??(if-null) gives a default fornull:missing ?? -1.??=assigns only if the variable is currentlynull.- Flow analysis. After
if (where != null), the compiler knows that inside the blockwherecannot benull, and promotes it fromint?toint, sowhere + 1compiles without any extra syntax. Promotion also followsreturn,throw,ischecks and&&. This is the tool you will use most, and it makes null-safe Dart read like ordinary code. !(the null assertion) says "I know this is not null" and turnsint?intoint, throwing at run time if you were wrong. Use it only wherenullwould be a bug in the program, never on user input.latepostpones initialization of a non-nullable variable, with a run-time check, as described above.
The field-promotion trap
Promotion works on local variables, but not always on fields. Given a class with a public field String? bio, the code if (p.bio != null) print(p.bio.length); is rejected with the same "potentially null" error. The reason is soundness: bio could be overridden in a subclass by a getter that returns a different value each time it is read, so a check on one read proves nothing about the next. The idiomatic fix is to copy the field into a local variable (final bio = p.bio; if (bio != null) ...) or to use a pattern, as you will see in the lesson on patterns. Since Dart 3.2, private final fields can be promoted, because the compiler can see every place they are declared.
Type tests, casts and dynamic
When a value's static type is general, such as Object?, you find out what it really is with is, and flow analysis promotes it just as it does for null checks:
String describe(Object? value) {
if (value == null) return 'nothing';
if (value is int) return 'an int, doubled ${value * 2}'; // promoted to int
if (value is String && value.isNotEmpty)
return 'text starting with ${value[0]}';
if (value is List<int>) return 'a list of ${value.length} ints';
return 'something else: ${value.runtimeType}';
}
void main() {
final things = <Object?>[
21,
'Zanzibar',
'',
[1, 2, 3],
4.5,
null,
];
for (final thing in things) {
print(describe(thing));
}
// dynamic switches checking off: this compiles, and fails only when it runs.
dynamic loose = 'hello';
try {
print(loose.lenght); // a typo the compiler cannot catch
} on NoSuchMethodError {
print('runtime error: no getter called lenght');
}
// Object? keeps checking on: the same typo would not compile.
Object? strict = 'hello';
print((strict as String).length);
}an int, doubled 42
text starting with Z
something else: String
a list of 3 ints
something else: double
nothing
runtime error: no getter called lenght
5After value is int, the compiler treats value as an int inside that branch, so value * 2 compiles. The && carries the promotion into its right-hand side, which is why value.isNotEmpty works; the empty string fails that test and falls through to the last line. Because Dart's generics are reified (the element type is kept at run time), value is List<int> really checks the element type, unlike Java, where it would be erased. The type argument written in angle brackets before the list literal gives the list the element type Object?; without it, Dart would infer one from the elements.
The second half shows why dynamic is dangerous. The misspelled lenght compiles, because dynamic tells the compiler to stop checking, and the mistake surfaces only when that line runs, as a NoSuchMethodError (caught here so the program can continue; exceptions are covered in the next lesson). With Object?, the same typo is a compile-time error, and to use the value as a string you must test it with is or cast it with as, which throws if the value has a different type. Prefer is with promotion: it handles the other case instead of crashing on it.
Common misconceptions
Misconception
"final means the object cannot change." final means the variable cannot be reassigned. A final list can still have elements added. For an object that can never change, use const, or a class whose fields are all final and whose members expose no way to modify it.
Misconception
"dynamic and Object? are the same." Both can hold anything, but Object? keeps type checking on: you must test or cast before calling specific methods. dynamic turns checking off, so mistakes compile and fail at run time. Prefer Object?.
Misconception
"The ! operator converts null into something safe." It does the opposite: it promises the value is not null and throws if it is. Reach for ??, ?. or a null check first.
Misconception
"Dart's % works like Java's." For negative left operands they differ: Dart's % returns a non-negative result for a positive divisor (-7 % 2 == 1), while Java's returns −1. Dart's remainder method matches Java's %.
Exercises
1. Variables, types and null safety
Warm-upComputationalWhat does this line print?
print('${7 ~/ 2} ${7 / 2} ${-7 % 3}');
2. Variables, types and null safety
CoreComputationalWhat does this program print?
String? find(String key) => key == 'a' ? 'apple' : null;
void main() {
final x = find('a')?.length;
final y = find('b')?.length;
print('${x ?? 0} ${y ?? 0} ${y == null}');
}
3. Variables, types and null safety
CoreComputationalWhich of these lines are compile errors in null-safe Dart? Choose every one.
4. Variables, types and null safety
StretchComputationalOn a native platform (not the web), what does this print? Type the number exactly. The largest 64-bit int is 9223372036854775807.
print(9223372036854775807 + 2);
5. Variables, types and null safety
Warm-upComputationalWhat does this program print?
void main() {
final values = <int?>[null, 4, null, 7];
var total = 0;
for (final v in values) {
total += v ?? 1;
}
print(total);
}
6. Variables, types and null safety
CoreComputationalWhat happens when this runs?
final a = [1, 2];
a.add(3);
const b = [1, 2];
b.add(3);
7. Variables, types and null safety
StretchHumanprofile.bio is a public field of type String?. Why does if (profile.bio != null) print(profile.bio.length); fail to compile?
Further reading and resources
- Variables
- Built-in types
- Sound null safetyHow null safety works, including flow analysis and late variables.
- The Dart type systemWhat "sound" means, and how inference works.