Is there any way to directly call function passed as an optional parameter while also be protected from null value error, in Flutter/Dart?
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.
Chen Li Yong
Currently, I'm a mainly mobile programmer (iOS, swift / obj-C) which currently lead and work in multiple projects.
Updated on December 16, 2022Comments
-
Chen Li Yong over 1 year
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).
-
Atish Shakya about 4 yearsDo you mean if this.onFocusChange(boolValue); returns null do someother function??
-
Chen Li Yong about 4 yearsNo, I mean if the onFocusChange is coming from an optional parameter, how to safely invoking this function while not checking whether this onFocusChange function is null or not?
-
Chen Li Yong about 4 years@AtishShakya I have fixed the example to minimize the confusion.
-
Dev about 4 yearstry
onFocusChange??(boolValue);
-
Chen Li Yong over 2 years@Dev wait, this is possible? I'll try it. If this is possible, then this is definitely more preferred than
onFocusChange?.call(boolValue)
.
-
-
Chen Li Yong over 2 yearsI found the solution.
onFocusChange?.call(parameter)
.