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.

3
  • @jamesdlin please check.
    – Josteve
    Jan 22, 2022 at 17:07
  • Have a look at this answer. It applies for your case as well.
    – Daniel
    Jan 22, 2022 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, 2022 at 17:39

1 Answer 1

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.

3
  • 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, 2022 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, 2022 at 18:17
  • 1
    Got it, thank you for your nice explanation, I appreciate it @Amir_P
    – Aegletes
    Jan 22, 2022 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.