Let's see an example of null unsafe code, and then fix it. To do that, follow these steps:
- In DartPad, make sure Null Safety is disabled. You can toggle Null Safety with the control at the bottom of the screen:
- Remove the default code in the main method, and add the following instructions:
void main() {
int someNumber;
increaseValue(someNumber);
}
- Create a new method under main that takes an integer and prints the value that was passed, incremented by 1:
void increaseValue(int value) {
value++;
print (value);
}
- Run your code. You should see a null error in the console, as shown in the following screenshot:
- Enable Null Safety with the switch at the bottom of the screen, and note that someNumber at line 3 raises a compile error before execution on someNumber: "The non-nullable local variable 'someNumber' must be assigned before it can be used."
- Add a question mark after the two int delcarations:
void main() {
int? someNumber;
increaseValue(someNumber);
}
void increaseValue(int? value) {
value++;
print (value);
}
- Note that the error has changed to: "The method '+' can't be unconditionally invoked because the receiver can be 'null'."
- Edit the increaseValue method, so that you check whether the value is null before incrementing it, otherwise you just return 1:
void increaseValue(int? value) {
if (value != null) {
value++;
} else {
value = 1;
}
print (value);
}
- Run the app and note that you find the value 1 in the console.
- Edit the increaseValue method again. This time, use the null-check operator:
void increaseValue(int? value) {
value = value ?? 0;
value++;
print (value);
}
- Run the app, and note that in the console you still find the value 1.
- Remove the question mark from the value parameter, and force the call to increaseValue with an exclamation mark:
void main() {
int? someNumber;
increaseValue(someNumber!);
}
void increaseValue(int value) {
value++;
print (value);
}
- Run the app, and note that you get an execution null exception.
- Finally, fix the code by initializing someNumber with an integer value:
void main() {
int someNumber = 0;
increaseValue(someNumber);
}
void increaseValue(int value) {
value++;
print (value);
}
- Now you should see the value 1 in the console again.