Reputation: 475
This was my Dart code after initializing fun by adding ?
However, it is still not working and throws an error that says "An expression whose value can be null must be null-checked before it can be dereferenced"
int add(int a, int b) => a + b;
Function? fun;
void main() {
fun = add;
var result = fun(20, 30);
print("Result is ${result}");
}
How do I null-check fun?
Upvotes: 1
Views: 1292
Reputation: 25936
You compare against a null, the analyzer deduces that after the successfull check the variable is not null:
void testFunction(Function? f) {
if (f != null) {
var result = f(20, 30);
print("Result is ${result}");
}
}
One caveat is it does not currently work with global variables:
The analyzer can’t model the flow of your whole application, so it can’t predict the values of global variables or class fields.
See https://dart.dev/null-safety#using-variables-and-expressions
Also note that there isn’t a null-aware function call operator, but you can write:
function?.call(arg1, arg2);
Upvotes: 1