Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 61 ยท Types and Operators

Null Safety: Nullable and Non-Nullable Types

Understand sound null safety in Dart: nullable T? versus non-nullable T, the ?., ??, ??= and ! operators, null checks and how type promotion removes casts.

Tony Hoare called the null reference his "billion-dollar mistake": a value that can be missing, but that nothing in the type warns you about. Dart's answer is sound null safety. A type like String can never hold null. If you want a value that may be missing, you write String?, and the compiler then forces you to deal with the missing case before you use the value.

The result is that "null pointer" crashes mostly turn into editor errors. In this lesson you will learn the two kinds of types, the operators that handle null, and type promotion, which keeps null-checking code short. Dart blocks are read-only; the stand-ins use TypeScript in strict mode, which has very similar rules.

Non-nullable and nullable types

Every type in Dart comes in two flavors:

  • int, String, Pizza: non-nullable. The value is never null.
  • int?, String?, Pizza?: nullable. The value is either an instance of the type or null.
DART
void main() {
  String name = 'Ada';
  // name = null;            // error: Null can't be assigned to String

  String? nickname = null;   // fine
  int? score;                // a nullable variable starts as null
  print(score);              // null

  // print(nickname.length); // error: nickname might be null
}

The last commented line is the heart of the feature. The analyzer reports something like "The property 'length' can't be unconditionally accessed because the receiver can be 'null'." You cannot call a method on a nullable value until you have shown the compiler that it is not null. Every T is a subtype of T?, so you can always pass a String where a String? is expected, but never the other way around.

flowchart TD
    A["Object?"] --> B["Object<br/>(never null)"]
    A --> C["Null"]
    B --> D["String"]
    B --> E["int"]
    A --> F["String?"]
    D --> F
    C --> F

Object? sits at the top; String? accepts either a String or null.

TypeScript Strict null checks (TypeScript stand-in, fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(5,13): error TS18047: 'nickname' is possibly 'null'.

Checking for null

The most direct way to use a nullable value is to compare it with null:

DART
String describe(String? nickname) {
  if (nickname == null) {
    return 'no nickname';
  }
  return 'nickname has ${nickname.length} letters';
}

After the if returns, the compiler knows nickname cannot be null on the remaining path. This is called type promotion: inside the checked branch, the variable's type is promoted from String? to String. Promotion works for local variables and parameters, and since Dart 3.2 also for private final fields (names that start with an underscore). It does not work for public fields or getters, because another part of the program could change them between the check and the use.

DART
class Profile {
  final String? _bio;
  String? bio;
  Profile(this._bio);

  int bioLength() {
    if (_bio != null) {
      return _bio.length;     // promoted: private final field (Dart 3.2+)
    }
    return 0;
  }

  int publicBioLength() {
    if (bio != null) {
      // return bio.length;   // error: a public mutable field is not promoted
      return bio!.length;     // needs the ! operator
    }
    return 0;
  }
}

A handy trick for fields and getters: copy the value into a local variable first. final b = bio; if (b != null) { ... b.length ... } always promotes.

Promotion also follows is checks and return, throw and continue paths, so the compiler understands code like this:

DART
int lengthOrFail(String? text) {
  if (text == null) throw ArgumentError('text is required');
  return text.length;         // promoted to String
}

The null-aware operators

Dart has a family of operators that make common patterns short. All of them contain a question mark.

Operator Name Meaning
a?.b null-aware access null if a is null, otherwise a.b
a?[i] null-aware index null if a is null, otherwise a[i]
a ?? b if-null a if it is not null, otherwise b
a ??= b null-aware assignment assign b to a only if a is null
a! null assertion treat a as non-null; throws if it is null
...?list null-aware spread spread a list only if it is not null
DART
void main() {
  String? city;

  print(city?.length);                // null  (no crash)
  print(city ?? 'unknown');           // unknown

  city ??= 'Oslo';                    // city was null, so it is assigned
  city ??= 'Bergen';                  // city is not null, nothing happens
  print(city);                        // Oslo

  List<int>? extra;
  var numbers = [1, 2, ...?extra];    // [1, 2]
  print(numbers);
}
TEXT
null
unknown
Oslo
[1, 2]

?. short-circuits the whole chain. In user?.address.city.length, if user is null the entire expression is null; Dart does not evaluate .address, .city or .length. The result type of a chain that used ?. is nullable, so you often finish with ?? defaultValue.

TypeScript Null-aware operators (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Note the one visible difference: a missing value in TypeScript is often undefined, while Dart only has null.

The null assertion operator

Sometimes you know more than the compiler. The postfix ! tells it "trust me, this is not null":

DART
void main() {
  Map<String, int> ages = {'Ada': 36, 'Alan': 41};
  int adaAge = ages['Ada']!;       // lookup returns int?, ! makes it int
  print(adaAge);                   // 36

  int missing = ages['Grace']!;    // throws at runtime
}

Looking up a key in a Map returns V?, because the key may be absent, so ! is a common sight there. But a wrong ! crashes with "Null check operator used on a null value". Treat every ! as a small bet that the value exists. Before you add one, ask whether you could use ?? defaultValue, an if check, or a different design that avoids the nullable type.

If you are tempted to scatter ! through your code, step back. A non-nullable parameter, a required named argument or a late variable (see late Variables and Lazy Initialization) often removes the question completely.

Designing with null

Null safety is also a design tool. Use a nullable type when "no value" is a real, expected state: an optional middle name, the result of a search that may find nothing. Use a non-nullable type everywhere else and require the caller to provide the value. Return null instead of throwing only when callers can reasonably continue without a result, and give the function a name or documentation that makes this clear.

One more pattern is worth knowing now. When a nullable value must be both checked and used in one go, a pattern can bind it: if (map['key'] case final value?) { ... }. Inside the braces value is non-null. Patterns get their own lesson later in the course.

TypeScript Promotion and the guard pattern (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between String and String? in Dart?

    A type without a question mark is non-nullable. Adding ? makes it nullable, so the variable may hold either a String or null.
  2. 2. What is the value of city ?? 'unknown' when city is null?

    The if-null operator ?? returns its left side unless that is null, in which case it returns the right side.
  3. 3. When does x! throw?

    The null assertion operator casts away nullability. If the value is actually null at runtime, it throws an error ("Null check operator used on a null value").
  4. 4. Which of these variables is NOT promoted to non-nullable by an if (x != null) check?

    Public mutable fields can change between the check and the use, so the compiler cannot promote them. Copy the value to a local variable or use !.
  5. 5. What does user?.address.city evaluate to when user is null?

    The null-aware access short-circuits the entire chain, so .address and .city are not evaluated and the whole expression is null.

Summary

  • T never holds null; T? holds a T or null. The compiler enforces this, which is why it is called sound null safety.
  • Check with == null or != null; the compiler promotes locals, parameters and private final fields (Dart 3.2+) inside the checked branch.
  • ?., ?[], ??, ??= and ...? handle missing values in a single expression; ?. short-circuits the whole chain.
  • ! asserts that a value is non-null and throws if you are wrong, so use it sparingly.
  • Use nullable types only where "no value" is a legitimate state.

Next, see how non-nullable variables can be filled in later in late Variables and Lazy Initialization.