why is the null-check of an outer variable isn't enough in dart?


Why does the below code give an error?

Function? fob;

void someMethod() {
    if(fob != null) {

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.


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.

Answered By – Amir_P

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *