Dart's Sound Null Safety: No More Null Errors
In Dart, variables can't be null unless you explicitly allow it. This flips the usual model, turning potential runtime null pointer crashes into compile-time errors you can fix immediately.
WHY IT EXISTS Null pointer exceptions are a frequent cause of app crashes. Sound null safety was introduced in Dart to eliminate this entire class of bugs by catching them at compile time, not runtime. It makes code more robust and predictable by forcing developers to explicitly handle the absence of a value.
THE MENTAL MODEL Think of null safety as an "opt-in" system for nulls. By default, every variable you declare is guaranteed to hold a real value. If you want to allow a variable to be null, you must explicitly tell the compiler by adding a ? to its type. This flips the model of many other languages where any object can be null by default.
HOW IT WORKS The Dart compiler and static analyzer enforce null safety. Types like String and int are non-nullable. They must be initialized with a non-null value before they are used. If you declare a variable as nullable, like String?, the compiler tracks its state. You cannot access its methods or properties (e.g., myNullableString.length) without first proving to the compiler that it is not null, usually with an if (myNullableString != null) check. This "soundness" means that if your code compiles without null safety errors, it is guaranteed not to throw a null pointer exception at runtime for any non-nullable type.
WHEN TO USE IT Sound null safety is the default and is not optional in modern Dart and Flutter code. You use non-nullable types for data that must always exist, like a user's ID or an item count in a shopping cart. You use nullable types (?) for data that is legitimately optional, such as a user's middle name or a field in a JSON response that might not be present.
WHEN NOT TO USE IT You cannot opt out of the system itself. The key is knowing when to use nullable vs. non-nullable types. Avoid the pitfall of making everything nullable just to make compiler errors go away; this defeats the purpose of null safety. Instead, think carefully about your data model. If a value can truly be absent, make it nullable and handle the null case explicitly. If it should never be null, keep it non-nullable and ensure it's always initialized properly.
ONE CANONICAL EXAMPLE In Dart, a standard type like int cannot hold null.
int itemCount = 1; // itemCount = null; // This line causes a compile-time error.
To declare a variable that can be null, you add a ? to the type.
String? optionalMessage = 'Welcome!'; optionalMessage = null; // This is allowed.
Before using a nullable variable, you must check it.
if (optionalMessage != null) { print(optionalMessage.toUpperCase()); }
Read the original → dart.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.