How to Handle Nullable Values in Flutter: Null Safety Guide

How to handle nullable values in Flutter: nullable types, the ! operator, late, required — plus a step-by-step migration of real pre-null-safety code.

Null safety still trips up beginners — and honestly, experienced developers switching from JavaScript or Python too. The concept is simple ("the type system tracks which values can be null"), but knowing how to handle nullable values in Flutter in practice — ? , ! , late , promotion, and migrating old code — takes deliberate learning. This guide is that practice, ending with a real pre-null-safety snippet migrated step by step. What null safety guarantees Tony Hoare called the null reference his "billion-dollar mistake": a value that claims to be a String but is actually null, crashing your app at runtime in front of a user. Dart's null safety moves that crash from runtime to compile time . The guarantee is simple: If a variable has a non-nullable type like String , it can never be null. The compiler proves it. No null dereference can happen at runtime for that variable — the bug becomes a compile error instead of a crash. The price is explicitness: wherever a value genuinely can be absent (an optional avatar URL, a not-yet-loaded user), you must say so in the type. That explicitness is the whole point — it forces every null case to be handled somewhere, deliberately. Step 1 — Nullable vs non-nullable types Append ? to make a type nullable. Without it, the type is non-nullable and the compiler enforces it: String name = 'Ada'; // non-nullable: can NEVER be null String? nickname = null; // nullable: null is allowed name = null; // COMPILE ERROR: can't assign null to a non-nullable variable This is why the classic beginner snippet fails: void main() { String? name; // nullable, defaults to null print(name.length); // COMPILE ERROR: 'name' can be null — did you mean 'name?.length'? } The compiler refuses to let you call .length on something that might be null. That's not…

Explore