What is null safety in Dart?
Short Answer
Sound null safety means the compiler distinguishes nullable (`String?`) from non-nullable (`String`) types and guarantees, at compile time, that a non-nullable variable can never hold null.
Before null safety, any variable could be null, which made NullPointerException-style crashes ("Null check operator used on a null value" in Dart) one of the most common runtime errors. With sound null safety, every type is non-nullable by default; you opt into nullability explicitly with a `?` suffix.
The compiler then enforces this everywhere: you must either check for null, provide a default with `??`, or assert non-null with `!` (the null assertion operator) before using a nullable value where a non-nullable one is expected. Because the guarantee is sound (not just a lint), the Dart compiler can also use this information to generate more optimized code.
Code Example
String? maybeName; // nullable
String name = maybeName ?? 'Guest'; // default with ??
String forced = maybeName!; // asserts non-null (throws if null)
void greet(String name) => print('Hello, $name');
// greet(maybeName); // compile error: String? isn't StringCommon Mistakes
- ×Overusing the `!` null-assertion operator to silence the compiler instead of actually handling the null case — this just moves the crash to runtime.
- ×Marking everything nullable "to be safe" instead of modeling which fields are genuinely optional.
Interview Tips
- →Distinguish sound null safety from a linter warning — Dart's guarantee is enforced by the type system itself, including across libraries.
Related Tools
JSON to Dart Converter
Convert JSON to Dart model classes. Generates fromJson, toJson, copyWith with null safety. Supports Freezed & json_serializable.
Dart Data Class Generator
Paste JSON and generate an immutable Dart data class with copyWith, toString, and equality — no JSON (de)serialization boilerplate.