Null safety in dart
Nil from backend developer to irritated frontend developer
Okay sometime we itself create some nil, not only from backend
Why Null safety ?
sometime while loading nil
or null
data in app, App will crash. To avoid it null safety
is important
so in this blog we will discuss about null safety in flutter
When will null affect the code
int? a;
print(a); // null
above code will not create any error. But below code will.
// (Note this code will not run)
int? a;
int? b = 2;
print(b); // 2
print(a); // null
print(a + b); // error
So when we trying to do something with null our code will crash
Null safety in flutter
Null safety can done in more ways
- With if condition
- Assertion operator(!)
- if null operator (??)
With if condition
its like avoiding the line with if condition
int? a;
int? b = 2;
if (a == null) {
print("a is null"); // a is null
} else {
print(a + b);
}
this is one type of avoiding null. But free advise don’t do with this type
Assertion operator(!)
use !
when you sure value is not null
Example
int? a;
int? b = 2;
if (b == 2) {
a = 2;
}
print(a! + b);
Here we assigned a = 2
so we can use !
. If not code will crash
int? a;
int? b = 2;
if (b != 2) {
a = 2;
}
print(a! + b); // code will crash here
(Note: use this when your sure that value is not null)
If null operator (??)
one of the safest way to handle null safety.
Here will assign any default value, if the value is null
Example
int? a;
int? b = 2;
print((a ?? 0 ) + b); // 2
Here the operator will check for null, If it is null, it will assign 0 (as i assigned 0 as default)
a
is variable. ??
if for checking value. 0
The default value you want
Free advice use this method for your null safety
int? a;
int? b = 2;
a ??= 0;
print(a + b); // 2
we can also handle like a ??= 0
. This method is like checking and assigning using ternary operator.
Same like for other data type to.
If any mistake or you need to shout me, comments session in always opened
நன்றி வணக்கம் || Thank you