Flutter › Dart Null Safety
What is null safety in Dart, and how does it help prevent a common category of runtime error known as a null reference exception?
BeginnerAnswer
Null safety is a Dart language feature that requires you to explicitly declare whether a variable is allowed to hold a null value or not, and by default every variable in Dart is considered non nullable, meaning the compiler guarantees it will always genuinely hold a real value and can never accidentally be null, which eliminates an entire common category of runtime crash, historically often called a null pointer exception in many other programming languages, by catching these kinds of mistakes at compile time instead of allowing them to only surface later as an unexpected crash while the app is actually running.
String name = 'Alex'; // Cannot ever be null
String? nickname; // Can be null, must be explicitly marked with a question markReal-world example A developer accidentally forgets to provide a value for a non nullable String field, and Dart's compiler immediately flags this as an error at compile time, preventing what would have otherwise very likely caused a genuine crash later in production.