Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 73 ยท Dart essentials

Null Safety

Understand Dart null safety: nullable types, the ?, !, ?? and ?. operators, late variables, flow analysis and the most common null mistakes in Flutter code.

A null reference is a value that stands for "nothing here", and calling a method on it crashes the program. The inventor of null called it his billion-dollar mistake. Dart answers this with sound null safety: the type system knows which variables may be null and which never can, and it refuses to compile code that could crash by accident.

Null safety is on by default in every current Flutter project, and you meet it in almost every line of real code: optional widget parameters, JSON fields, text controllers. This lesson shows how to read and write it fluently. Dart code here is read-only; the JavaScript stand-ins below imitate the operators so you can try the logic.

Non-nullable by default

A plain type such as String or int can never hold null:

DART
String name = 'Ada';
name = null;          // compile error: 'Null' can't be assigned to 'String'

To allow null, add a question mark to the type:

DART
String? nickname;     // starts as null
nickname = 'Ad';
int? age;             // may hold an int or null

String? and String are different types. A String? might be missing, so Dart will not let you use it as if it were definitely there:

DART
String? nickname;
print(nickname.length);   // compile error: the property 'length' can't be
                          // unconditionally accessed because the receiver can be 'null'

The error shows up while you type, long before a user taps a button. That is the whole point.

Four tools for nullable values

?. Call a member only if not null.
?? Use a fallback when null.
! Promise it is not null. Risky.
if checks Dart remembers what you checked.

Prefer the first, second and fourth. Use the bang operator rarely.

1 / 2

The null-aware operators

Safe access: ?.

a?.b evaluates to null if a is null, and to a.b otherwise. It stops the whole chain:

DART
String? nickname;
int? length = nickname?.length;      // null, no crash
String? shout = nickname?.toUpperCase();

The result type is also nullable (int?), because the call might have been skipped.

Fallback: ?? and ??=

DART
String shown = nickname ?? 'anonymous';   // right side when left is null
nickname ??= 'guest';                      // assign only if currently null

?? turns a nullable value into a non-nullable one, so it is the cleanest way to settle "what if it is missing".

The bang operator: !

value! tells Dart "I know this is not null." If you are wrong, the program throws at run time:

DART
String? maybe = readFromSomewhere();
print(maybe!.length);   // throws a null check error if maybe is null

Each ! is a spot where you took responsibility away from the compiler. Use it only when something Dart cannot see guarantees the value, and prefer ??, ?. or an if check otherwise. A codebase full of ! has recreated the problem null safety solves.

Null-aware collection and spread

DART
List<int>? extra;
final all = [1, 2, ...?extra];      // ...? skips a null list
final firstOrNull = extra?[0];      // ?[] indexes only when not null

Flow analysis: Dart remembers your checks

After you check a local variable for null, Dart promotes it to its non-null type within that branch:

DART
void printLength(String? text) {
  if (text == null) {
    print('nothing');
    return;
  }
  // Here Dart knows text is a String, not String?
  print(text.length);
}

int lengthOrZero(String? text) {
  return text != null ? text.length : 0;
}

Promotion also works after an early return, throw or continue, as the first function shows. It works for local variables and parameters, but not for fields of a class, because another part of the program could change a field between the check and the use. For fields, copy to a local variable first:

DART
class Profile {
  String? bio;

  int bioLength() {
    final text = bio;            // local copy
    if (text == null) return 0;
    return text.length;          // promoted
  }
}

Patterns give another style. This if-case checks and unpacks in one step:

DART
if (bio case final text?) {
  print(text.length);   // text is a non-null String
}

Required parameters and nullable fields

Named parameters are optional, so a non-nullable one needs a default or must be required:

DART
class Greeting {
  final String name;
  final String? subtitle;       // may be missing

  const Greeting({required this.name, this.subtitle});
}

const a = Greeting(name: 'Ada');                       // subtitle is null
const b = Greeting(name: 'Ada', subtitle: 'Welcome');

Flutter widgets use this pattern constantly. Text('Hi', style: null) is allowed because style is declared as TextStyle?, while Text() without data is an error because data is required.

late variables

late means "I will set this before I read it, but not at declaration":

DART
class Loader {
  late final String config;      // assigned once, later

  void start() {
    config = 'loaded';
  }
}

late final value = expensiveCalculation();   // lazy: runs on first read

Reading a late variable before it is assigned throws a LateInitializationError. Typical use in Flutter is late final controller in a State class, set up in initState (see StatefulWidget and setState). If something truly may be missing, a nullable type is the honest choice; late is for things that are always set before use.

Common mistakes

  1. Scattering ! to silence errors. The error was a warning about a real case. Handle null instead.
  2. Using late instead of ? for values that can legitimately be absent, such as a selected item.
  3. Checking a field, then using it. Fields do not promote; copy to a local variable.
  4. Forgetting the result of ?. is nullable. user?.name.length is int?, so you still need ?? 0 before doing arithmetic.
  5. Treating empty as null. An empty string '' is not null. Use text == null || text.isEmpty or the isNullOrEmpty pattern from your own helper.

Stand-ins in JavaScript

JavaScript has ?. and ?? with the same meaning, so they make a good practice playground. Remember that JavaScript has no static check: nothing stops you from calling a method on null, which is exactly the crash Dart prevents.

JS Safe access and fallbacks

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

No output.

The second stand-in shows what ! really does: it adds a run-time check that throws. A small helper imitates it, next to the safe alternative.

JS A bang operator as a function

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does String? mean?

    The question mark makes the type nullable. A plain String can never be null.
  2. 2. What does nickname ?? 'guest' evaluate to when nickname is null?

    ?? returns the right side when the left side is null, and the left side otherwise.
  3. 3. Why does Dart not promote a nullable class field after an if (field != null) check?

    Only local variables and parameters are promoted. Copy the field into a local final variable, then check that.
  4. 4. What happens when you read a late variable before assigning it?

    late shifts the check from compile time to run time. If it is read too early, it throws.

Summary

  • Types are non-nullable by default; add ? to allow null.
  • Use ?. for safe access, ?? for fallbacks and ??= for lazy defaults.
  • ! skips the safety net and throws if wrong, so use it sparingly.
  • Dart promotes local variables after null checks, but not class fields.
  • late defers initialization; use it only when the value is always set before it is read.
  • All Dart here is read-only; the TryIts are JavaScript stand-ins.

Next: Classes, Constructors and Mixins