Why does the below code give an error?
Function? fob;
void someMethod() {
if(fob != null) {
fob();
}
}
Why is this null-check not enough and fob(); here gives an error? What could be happening between the if check and the call to the function that it could be null again?
I know this works when I declare a local variable to the function, but I just want to understand why dart works the way it does.
CodePudding user response:
Since this variable is not an inline variable, we can't be sure that it will not change between checking and using. You may be calling another function inside your condition block and that function sets that global variable to null. So to have sound null-safety type promotion only works on inline variables.
In your case, you can use fab?.call() without checking the variable isn't null or fab!() inside your condition block. Read more here.
CodePudding user response:
Don't think like a human while coding! Think about how the compiler interprets a piece of code. The null aware operators are intended to make us think (while coding) that a NullPointerException might cause at run-time.
fob(); can be null, so when you try to call, the compiler reminds us it can be null. So you add the if condition to avoid the same: if(fob != null). So you made sure that it will never be null. But the compiler still thinks it can be null since you have declared it so. Function? fob;
That's where the ! comes to act. It says compiler, "Hey I have made sure that it won't be null stop showing error". So use "!" wisely. Use ! if and only if you are sure it won't be null. Literally, just do a null check before using !(**Not necessary in every scenario!).
