Null : something whose value hasn't been decided yet
void whatIsYourFood(Food f) { if (f == null) print('need a food name'); else print(f.recipe.toString()); }
If f's value is null, you can just do a null check in the if statement like the code above.
So why does flutter bother using null safety?
Because a developer might accidentally forget that they need a null check in the if statement.
flutter uses null safety to remove the possibility of this kind of mistake.
Now let's go over null safety.
You can't assign null to a non-nullable variable.
void main() { String name; int age = null; print(name); print(age); }
Before null safety, this code gave no errors and printed null just fine,
but now null can't be assigned to a variable.
You don't need a null check for non-nullable variables.
int number = 4; void main() { if (number == null) return; int sum = number + 5; print(sum); }
When you write code like this, you get a message saying int is null-nullable so there's no need to filter out null.
But
when expressing a case like Food favorite = null, where there's no favorite food yet, you need a null value.
Or sometimes you write code so a variable doesn't get a value right when it's declared, but can be assigned later.
Since so far we know that null can't be assigned to a variable, the downside is that we can't express null.
That's why there are nullable types.
You can assign null by adding ? to an existing variable type, like String?,
and you must always do a null check before using it.
Or you can use the null assertion operator !
to use it without a null check, which isn't safe, on the assumption that it's definitely not null.
Using ! is the same as turning a String? variable into a String.
'Variables in a Class' must be initialized at the same time they're declared.
class Person() { String name; String nameChange(String name) { this.name = name; return name.toUpperCase(); } } void main() { Person p = Person(); if (p.name == null) print('need a name'); else print(p.nameChange(p.name)); }
Before null safety there was nothing wrong with code like this,
but when developers handle a lot of variables, the problem is they might forget the null check.
So with null safety, at compile time you get a message saying name must be initialized when declared and that the null check is meaningless.
There are 3 ways to solve this.
- Use the require keyword
- Use the late keyword
- Add ? to turn it into a Nullable type, then use it with null checks