Sub topic 1
Why null safety exists
Null safety changes where a whole class of Dart bugs shows up. Without it, you find them when a user's app crashes. With it, you find them when you compile. This chapter covers the problem that null safety solves and the design decisions behind it. The syntax comes in the chapters that follow.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Dart: variables, functions, classes and constructors.
- Recognize Dart's static types and type inference, for example that
var x = 3;givesxthe typeint. - Run Dart code with
dart runor in DartPad, so you can try the examples.
You don't need any knowledge of null-aware operators or late. Later chapters introduce them.
What null is and why it is risky
null is a special value that means "no object here." A variable can hold it when nothing has been assigned yet. A function can return it when it has nothing to give back, such as a lookup that finds no match. A caller can pass it to say "I didn't provide this."
The risk comes from what happens next. Code that receives a value usually assumes it is a real object and calls a method on it. If the value is null, that call has no target and the program fails.
Tony Hoare, who introduced null references in the ALGOL W language in 1965, later called them his "billion-dollar mistake." The language let any reference be null, and the type system could not tell the programmer which references might be. The problem is that nothing in the code marks the dangerous places.
How the problem looked in Dart before null safety
Before Dart 2.12, every type in Dart included null. A variable declared as String could hold a string or null. The type String made no promise that a string was actually there.
A function like this looked harmless:
int lengthOf(String s) => s.length;Under the old rules, a caller could pass null and the compiler would accept it. The crash came later, at runtime, inside lengthOf. The error was a NoSuchMethodError saying that length was called on null.
Three things made this worse than it sounds:
- The failure is far from the cause. The crash happens where the value is used. The mistake happened where the
nullwas created, which could be many calls earlier. - The signature lies. A parameter typed
Stringsuggests a string will be present. A reader has to check the whole call chain or the documentation to know. - Defensive checks are noisy and inconsistent. Teams wrote
if (s == null)checks in some functions and forgot them in others. Some code documented "must not be null" in comments, which the compiler cannot enforce.
You can reproduce this runtime failure today by turning off static checking with dynamic:
void main() {
dynamic value = null;
print(value.length); // throws NoSuchMethodError at runtime
}The compiler accepts this because dynamic skips type checks. The program then fails when it reaches the call. The exact error text differs between Dart versions, but it is always a NoSuchMethodError because null has no length. Before null safety, ordinary typed code behaved the same way.
Where null comes from in everyday code
Null is not an exotic case. These common situations produce it:
| Situation | Example |
|---|---|
| A variable declared but not yet assigned | A field that a method fills in later |
| A lookup that finds nothing | `map['missing-key']` returns `null` |
| An optional parameter left out | A caller omits an argument that has no default |
| A search with no match | A helper that returns `null` when nothing is found |
| Data from outside the program | A JSON field that is absent or explicitly `null` |
Each of these is a legitimate design. Absence of a value is a real part of many programs. The trouble was that the type system did not record it.
The idea behind null safety
Dart's solution is to make absence part of the type. The rule is:
- A type such as
Stringmeans "a string, never null." - A type such as
String?means "a string, or null."
This is called being non-nullable by default. Every type you write without ? promises that a value is present. If you want a value to be absent sometimes, you say so with ?, and the compiler then requires you to handle the null case before you use the value.
Here is the effect on the earlier mistake:
void main() {
String name = 'Ada';
name = null; // compile-time error
print(name);
}This code does not compile. The analyzer reports that a value of type Null can't be assigned to a variable of type String. You see the problem in your editor, and it never reaches a user.
The next chapter covers the T versus T? syntax in detail. For now, the point is that the type tells the truth about whether a value can be absent.
Moving the error from runtime to compile time
The central benefit is when you learn about the mistake. The diagram below compares the two timelines.
Catching a bug at compile time is cheaper for several reasons. The error message points at the exact line. You don't need a test or a user to reach that path. Rare paths, such as an error branch that runs once a month, get checked as thoroughly as common ones.
A runtime failure still possible: handling it deliberately
Null safety does not make null vanish. It makes you decide what to do with it. Here is a function that really can return nothing:
String? findName(int id) => id == 1 ? 'Ada' : null;
void main() {
print(findName(1)!.length); // 3
print(findName(2)!.length); // throws at runtime
}The return type String? tells every caller that the result may be absent. The ! after findName(2) tells the compiler "I know this is not null." Here that claim is false for id 2, so the program throws an error with the message "Null check operator used on a null value."
Two things are worth noticing:
- The compiler forced you to write something. Without the
!or a null check, the callfindName(2).lengthwould not compile. - The risky spot is now visible in the source. You can search for
!and see every place where the code asserts that a value is present. A later chapter covers when this is acceptable and which safer alternatives exist.
What "sound" adds
Dart's null safety is called sound. Soundness means that if the compiler decides an expression of type String is non-null, it really is non-null at runtime. The compiler is allowed to rely on this fact. The next chapters explain it further, but there are two practical consequences you should know now:
- You can trust types when reading code. A parameter typed
Stringwill never receivenull, so you can delete defensive checks that were only there for safety. - The compiler and runtime can optimize. Because some values cannot be null, generated code can skip checks it would otherwise need.
A less strict system, which only warns about likely problems, gives you neither benefit. A warning may be wrong, so you cannot rely on it.
Trade-offs and limits
Null safety has costs, and it helps to know them so the rules feel reasonable.
- More up-front decisions. You must decide for each variable, field and parameter whether it can be absent. Many people find this clarifies the design, but it takes effort at the start.
- Initialization rules are stricter. A non-nullable field must have a value by the time the object exists. This is why Dart has
requirednamed parameters andlate, covered in later chapters. - It covers null, not every bug. An empty string, an index out of range, or a wrong number is still your responsibility. Null safety only removes failures where an absent value is used as if it were present.
- Runtime checks remain at the boundaries. Operations such as
!, a cast, orlatevariables can still throw. Null safety narrows where those can happen, but it does not make failure impossible.
Null safety in the Dart ecosystem
Null safety arrived in Dart 2.12 in March 2021. Sound null safety became mandatory with Dart 3 in 2023, which no longer runs code that opts out. Flutter and the core Dart libraries are written against it. Legacy code and mixed code are covered in the last chapter of this tutorial.
Summary of the key points
- Before null safety, every Dart type allowed
null, so mistakes surfaced as runtime crashes far from their cause. - Null safety puts absence into the type:
Stringis never null,String?may be. - This moves a class of errors from runtime to compile time and makes signatures honest.
- Null is still a valid and useful value. The change is that you have to handle it deliberately.
Exercise
A teammate says: "Null safety means my app can never throw an error about null." Using the findName example from this chapter, explain what is wrong with that claim and what null safety actually guarantees.
Show answer
Null safety does not remove every runtime null failure. In the example, findName(2)! still throws at runtime, because ! tells the compiler to trust you that the value is not null. What null safety guarantees is that a value of a non-nullable type such as String is never null, and that you cannot use a nullable String? as if it were present without first handling or explicitly asserting the null case. Failures can then only come from places the source marks, such as !.
Exercise
A function is declared as int total(List<int> values). Before null safety, which kinds of calls could crash at runtime, and why does the same signature give stronger guarantees under null safety?
Show answer
Before null safety, a caller could pass null for values, or the list could contain null elements, and the compiler accepted both. A call such as values.length or adding the elements then failed at runtime. Under null safety, List<int> means the list itself is non-null and its elements are non-null int values. The compiler rejects calls that pass null, so the function body needs no defensive null checks.