Explain it simply
Explain it simply
Picture two kinds of parcel. A box labelled "always contains something" is a String: when you open it there is always text inside. A box labelled "might be empty" is a String?, and only after opening it do you know whether you got an item or nothing.
In many languages every box can quietly be empty, and you only learn that when your hand goes into an empty one and the app crashes. Dart makes you write the label yourself and the compiler stops you from using a maybe-empty box before looking inside. That way the crash of "using a value that is not there" is caught while compiling, before the app ever runs.
Problem → Why → Solution
The problem: looking up a key that is not in the map
You have a map of user ids and names, and you take the name for id 'u3' and count its letters. 'u3' is not in the map. In older languages this code looks fine and passes testing; only in production, when an unknown id arrives, does it crash with a complaint that you cannot call length on null.
In Dart a map lookup returns the value type followed by ?, not the plain value type, so the problem is visible at the moment you write the line. The compiler is saying: this box may be empty, do not put it into a variable that promises to hold something.
void main() {
final users = {'u1': 'Aye', 'u2': 'Su'};
String name = users['u3']; // compile error: String? is not String
print(name.length);
}Why does the compiler reject this?
The type of users['u3'] is String?, because a missing key returns null. Putting it into a String variable gives "A value of type 'String?' can't be assigned to a variable of type 'String'." You have to make a choice about the missing case: check it, give a default, or decide that absence is an error.
Core concept: nullable types, null-aware operators and promotion
Every Dart type comes in two flavours. String is a promise that the value is always text; String? means "text or null". null is a real value of its own, and only nullable types such as String?, int? and List<Item>? may hold it. Assigning it anywhere else is rejected before the program runs: "A value of type 'Null' can't be assigned to a variable of type 'String'." Because the rule is sound, a String variable really is never null at runtime, and the compiler can build on that guarantee.
A nullable value is a box that may be empty, so Dart will not let you call members on it directly. name.isEmpty on a String? stops with "Property 'isEmpty' cannot be accessed on 'String?' because it is potentially null." You have four ways out: check with if (name != null) and use the value inside, use ?. to access a member only when the value exists, supply a fallback with ??, or assert with ! that you know it is not null. The first three are safe; the last one is a promise you must keep yourself.
The null-aware operators do the checking for you. a?.length evaluates to null instead of crashing when a is null, and in a chain such as user?.address?.city?.length the first null short-circuits the rest. a ?? b gives a when it is not null and b otherwise. a ??= b assigns b only if a is currently null, which is handy for lazy defaults. The same idea exists for indexing (list?[0]) and for spreading a nullable collection into a list (...?maybeItems). The result of ?. is itself nullable, so you usually finish a chain with ?? to get a plain value back.
Flow analysis ties it together. After if (name == null) return ..., the compiler knows name cannot be null for the rest of the function and promotes it from String? to String, so name.length compiles. This works for local variables and parameters as long as nothing reassigns them in between. It does not work for ordinary fields: between your check and your use, another method or other code could change the field, so Dart refuses to trust it. Public and mutable fields are never promoted; the fix is a local copy, final nick = nickname;, which you can check and promote safely. Dart 3.2 and later also promote private final fields.
- String: a value is always there
- String?: the value may be missing
- Check first, or use ?. and ??
- After the check it counts as String
A nullable type is a question the compiler makes you answer before you use the value.
General pattern
Type name = value; // never null
Type? maybe; // may be null
maybe?.member // null if maybe is null
maybe ?? fallback // fallback if maybe is null
maybe ??= fallback; // assign only when it is null
maybe! // assert non-null (throws if wrong)
if (maybe != null) { /* maybe is promoted to Type in here */ }The ? after a type declares that null is allowed. ?., ?? and ??= are the safe operators, while ! is a promise to the compiler and throws at runtime if you are wrong. Inside the if (maybe != null) block promotion lets you use members directly.
Example: handling values that may be missing
In this program the map's value type is itself String?, so null has two sources: a missing key (u9) and a null value (u2). greet() checks for both with a single if and then relies on promotion. int.tryParse returns null when the text is not a number, so the int? is given a default with ??. Watch how ?? and ??= replace what would otherwise be several ifs.
final users = <String, String?>{'u1': 'Aye', 'u2': null};
String greet(String id) {
final name = users[id]; // String?: the key may be missing, or the value null
if (name == null) {
return 'Hello, guest';
}
return 'Hello, $name (${name.length} letters)';
}
int? parseAge(String text) => int.tryParse(text);
void main() {
print(greet('u1'));
print(greet('u2'));
print(greet('u9'));
final age = parseAge('abc');
print(age);
print(age ?? 18);
print(age?.isEven);
String? cached;
cached ??= 'loaded';
cached ??= 'ignored';
print(cached);
print(users['u9']?.toUpperCase() ?? 'NONE');
}Code breakdown
- Nullable value type
final users = <String, String?>{'u1': 'Aye', 'u2': null};The value type is String?, so 'u2': null is allowed. With plain String this line would not compile.
- Lookup returns String?
final name = users[id];A map lookup returns V?, so name has type String?. It is null both when the key is missing and when the stored value is null, and you cannot tell the two apart.
- Promotion by early return
if (name == null) {This block leaves the function with return, so below it name cannot be null. The compiler promotes name to String and no ! is needed.
- Using the promoted value
return 'Hello, $name (${name.length} letters)';name.length compiles only because of promotion. Delete the if (name == null) check and you get "Property 'length' cannot be accessed on 'String?' because it is potentially null."
- Fallback with ??
print(age ?? 18);'abc' is not a number, so age is null and ?? supplies 18. The neighbouring age?.isEven does not call the member on null and simply evaluates to null.
- Assign only when null
cached ??= 'loaded';The first ??= assigns 'loaded' because cached is null. The second ??= does nothing because cached already holds a value, so 'loaded' is what gets printed.
Hello, Aye (3 letters)
Hello, guest
Hello, guest
null
18
null
loaded
NONEThe ! operator: use it sparingly
value! tells the compiler: this is not null, trust me. If you are right, the type stops being nullable and you carry on; if you are wrong, Dart throws "Null check operator used on a null value" at runtime. So ! switches off null safety's protection by your own hand, and it brings back the null crash of older languages. Use it only when you can prove that null is impossible at that spot; otherwise supply a default with ?? or decide explicitly what null should mean.
void main() {
final stock = {'apple': 3};
print(stock['apple']! + 1); // fine: we know this key exists
try {
print(stock['fig']! + 1); // the key is missing
} catch (e) {
print('caught: $e');
}
final figs = stock['fig'] ?? 0; // better: decide what "missing" means
print(figs + 1);
}late and required
late is a promise: this variable will be initialized later rather than at its declaration, and always before it is read. If you read it before keeping that promise, Dart throws a LateInitializationError at runtime. The form with an initializer, late final x = expensive();, is lazy: the expression is evaluated once, the first time the variable is read. required forces callers to pass a named parameter; leaving it out is the compile error "Required named parameter 'name' must be provided." That is clearer than making the parameter nullable and allowing null.
late String config;
class Report {
final String title;
late final String body = _render(); // runs on first read, not in the constructor
Report({required this.title});
String _render() {
print('rendering $title');
return 'Report: $title';
}
}
void main() {
try {
print(config); // read before assignment
} catch (e) {
print(e);
}
config = 'prod';
print(config);
final r = Report(title: 'Q3');
print('created');
print(r.body);
print(r.body);
}In real projects
Where this shows up in real projects
Null shows up wherever an app accepts data from outside. A JSON response from an API may leave fields out, database columns can be nullable, a user can leave a form empty, and a Map lookup or int.tryParse reports "not there" with null. Declaring middleName as String? and email as required String in a User model writes the contract, what must exist and what may not, into the type itself.
In Flutter code, parameters like required this.title are everywhere, and the compiler prevents you from building a widget without the data it needs. For a team the benefit is that "can this be null?" no longer needs to be asked in code review, because the type answers it. If you deal with nulls at the boundary where data enters the program and the rest of the code uses only non-nullable types, the checks live in one place.
Common mistakes
Common mistakes
1. Sprinkling ! everywhere to silence the compiler
Writing users['u3']!.length makes the error disappear, but when the key is missing the app crashes with "Null check operator used on a null value"; you hid the problem instead of solving it. Supply a default with ??, or check for null and decide what should happen.
2. Expecting a field to be promoted
In a class with String? nickname;, writing if (nickname != null) { return nickname.length; } produces "Property 'length' cannot be accessed on 'String?' because it is potentially null.", and the context line adds "'nickname' refers to a public property so it couldn't be promoted." Copy it with final nick = nickname; and check nick instead.
3. Making everything nullable, or using late carelessly
Making everything String? "just in case" spreads null checks through every line that touches it. Make a value nullable only when absence is real. Use late only when you are sure the variable is assigned before it is read; otherwise you swap a compile error for a LateInitializationError at runtime.
Best practices
Best practices
- Make a value nullable only when it is genuinely allowed to be absent; keep everything else non-nullable.
- Deal with null at the boundary (JSON, forms, database): give it a default with ?? or parse it into a model object as early as possible.
- In production code use ! only after a local check that proves the value exists; prefer ?., ?? and promotion for everything else.
- Mark every named constructor parameter that must be provided as required, which is clearer than making it nullable and allowing null.
Mini challenge
Mini challenge: a safe profile summary
Write a summary() function that takes a JSON-like Map<String, Object?> and copes with missing fields without crashing. You may not use !.
- Read name as a String? and fall back to 'anonymous' when it is null
- Read age as an int?: 'age unknown' when null, otherwise something like 'age 31'
- Get the number of tags with ?. and ?? (0 when the list is missing)
- Split email on '@' and show the domain, or 'no email' when there is none
- In main(), print summary() for a full map, a map containing nulls, and {}
String summary(Map<String, Object?> json) {
// TODO: read name (String?), age (int?), tags (a list) and email (String?)
// TODO: name falls back to 'anonymous'
// TODO: age null -> 'age unknown', otherwise 'age <n>'
// TODO: tag count with ?. and ??, email domain with ?. and split('@')
throw UnimplementedError();
}
void main() {
// TODO: print summary(...) for a full map, a map with nulls, and {}
}Expected: Aye, age 31, 2 tags, example.com anonymous, age unknown, 0 tags, no email anonymous, age unknown, 0 tags, no email
Show hint
Casting a map value with (json['name'] as String?) gives you a String?. For tags write (json['tags'] as List<Object?>?)?.length ?? 0, and for the domain email?.split('@').last ?? 'no email'. Put the cast in parentheses so it cannot be confused with ??.
Show solution
String summary(Map<String, Object?> json) {
final name = (json['name'] as String?) ?? 'anonymous';
final age = json['age'] as int?;
final tags = json['tags'] as List<Object?>?;
final email = json['email'] as String?;
final ageText = age == null ? 'age unknown' : 'age $age';
final tagCount = tags?.length ?? 0;
final domain = email?.split('@').last ?? 'no email';
return '$name, $ageText, $tagCount tags, $domain';
}
void main() {
print(summary({
'name': 'Aye',
'age': 31,
'tags': ['dart', 'flutter'],
'email': 'aye@example.com',
}));
print(summary({'name': null, 'tags': []}));
print(summary({}));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- String is a promise of never-null, String? declares that null is allowed, and thanks to sound null safety the promise holds at runtime too.
- ?. gives null when the receiver is null, ?? supplies a fallback, and ??= assigns only when the variable is null.
- Checking a local variable with if promotes it; for a public or mutable field take a local copy first.
- ! throws if it meets null at runtime, late throws a LateInitializationError when its promise is broken, and a missing required argument is a compile error.
Dart language overview — Dart