2

From this answer I understand that I can check for null value before calling a function passed as optional parameter:

myFunction ({ Function onFocusChange }) {

    if(onFocusChange != null) {
       onFocusChange(boolValue)
    }

}

I also understand that there's an optionality concept like Swift and Kotlin in Flutter, using "?" operator, though they all have their own quirks.

What I'm asking is if there's any way to call the optional function and silently fail if it's null, like in Swift:

onFocusChange?(boolValue);

I tried to add the question mark on Flutter, and it immediately tries to evaluate the "onFocusChange" as boolean (ternary operator).

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124

1 Answers1

1

I wondered the same thing. I tried the suggested onFocusChange??(boolValue);, but that didn't work for me. (Maybe due to a version difference?) What I ended up doing was (onFocusChange ?? () {})(); and that worked for me to keep it all on one line. Still doesn't have the simplicity I was hoping for, but I prefer it aesthetically over the multi-line code checking for null. Don't know if dart is smart enough to not actually call the empty function when onFocusChange is null, or how much of a performance hit it might be, if any, if this sort of thing were scattered throughout one's code.