Null Safety Essentials
Understand Dart's sound null safety system to write safer code by managing nullable and non-nullable types effectively. Learn how to use the late keyword and null-aware operators like ??, ?. and ! to handle potentially empty values while avoiding common null-related errors.
In older programming languages, attempting to access a variable that held no data (a null value) was the most common cause of application crashes. Dart 3 solves this problem with sound null safety. This means that by default, variables cannot hold null. The compiler forces us to explicitly declare when a variable is allowed to be empty, and it forces us to handle that emptiness safely before the program runs.
Non-nullable by default
As we saw in earlier lessons, standard variables are completely non-nullable. If we want a variable to accept a null value, we must append a question mark (?) to the data type.
Line 2: We create a strictly non-nullable
Stringvariable. By omitting the question mark, we guarantee to the compiler that this memory space will always contain valid text and can never safely hold anullvalue.Line 3: We use the
?type modifier to declare a nullableString. This explicitly signals that the variable is allowed to exist without any underlying data, enabling us to safely store the intentional absence of a value (null).Lines 5—6: We retrieve and output the contents of both containers to the console, demonstrating that Dart can smoothly handle and display both guaranteed data and
nullstates without crashing.
Definite assignment and the late keyword
Dart is smart enough to track local variables inside functions. It uses a rule called definite assignment. This rule states that we can declare a non-nullable variable without an initial value, but we must assign a value to it before we try to read it.
Line 2: We reserve memory for a strictly non-nullable whole number but intentionally leave it uninitialized. Because it is not marked with a
?, the compiler knows this container is not allowed ...