2

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.

Aegletes
  • 460
  • 2
  • 6
  • 17
  • @jamesdlin please check. – Josteve Jan 22 '22 at 17:07
  • Have a look at [this answer](https://stackoverflow.com/a/65035575/11946665). It applies for your case as well. – Daniel Jan 22 '22 at 17:19
  • Thank you @Daniel but I am still not exactly sure about the reasoning here. Could you explain it to me? I've seen the post you sent and it talks about getters possibly changing the variable to null, right? Why is dart not able to check this though? What could a getter be doing there, is there any example about this? – Aegletes Jan 22 '22 at 17:39

1 Answers1

2

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.

Amir_P
  • 8,322
  • 5
  • 43
  • 92
  • Thank you for your answer @Amir_P, I know I can do a fab?.call() in this case, but I was just giving a simple example, wanted to know why this is happening. So what you are saying is basically, if the variables gets set to null even through a function that is called within the initial function, the compiler has no way of knowing this, right? From the link you sent, I guess they are still kinda looking into it. – Aegletes Jan 22 '22 at 17:45
  • Right, compiler has no way to be sure that it's not null when you're using it. As far as I found out, solutions are very limited. Some cases can be handled like final variables or there may be a way to implicitly force non-nullability to your expressions after checking if it's not null but I guess the way it's working now is as expected and clear. @Aegletes – Amir_P Jan 22 '22 at 18:17
  • 1
    Got it, thank you for your nice explanation, I appreciate it @Amir_P – Aegletes Jan 22 '22 at 19:06