Null Safety
In simple words null safety in dart means variables cannot contain null value by default. This reduces the risk of runtime bugs and makes your code error-free. This feature is called Sound Null Safety in dart. A null safety feature is added to Dart 2.12 version.
What Is Null?β
The meaning of Null in a programming language is no value or absence of value. For E.g int age = null;
. This code will
not work in dart recent version.
Exampleβ
Note
A value of type Null canβt be assigned to a variable of type int
.
Problem With Nullβ
Programmers do have a lot of difficulties while handling null
values. They forget that there are null values, so the
program breaks. Here null
mostly acts as time bomb for programmers, which is ready to break the program.
Note
Common cause of errors for programming languages, in general, comes from not properly handling null values.
Non-Nullable By Defaultβ
Variables cannot be null by default. If you attempt to assign a null value, it will give a compile-time error.
int productId = 20; // non-nullable
int productId = null; // give error
How To Define Null Valueβ
As you know with dart sound null
Safety you cannot provide a null
value by default. If you are 100% sure to use it then you can use ?
to the type declaration.
Syntaxβ
int? productId = null; // Works
Exampleβ
Important Point In Dart Nullβ
- Null means no value.
- Common error in programming is caused due to null.
- Dart 2.12 introduced sound null Safety to solve null problems.
- Non-nullable type is confirmed to never be null.
- You can define null value on your own if necessary.