Null-aware function call?

Issue

Dart has some null-aware operators, i.e. it is possible to do

var obj;
obj?.foo(); // foo is only called if obj != null.

Is this also possible for functions that are stored or passed to variables? The usual pattern is

typedef void SomeFunc();

void foo(SomeFunc f) {
  if (f != null) f();
}

It would be nice to have some null-aware calling here, like f?(). Is there anything we can use to not litter the code with null checks for those callbacks?

Solution

Form the docs:

Dart is a true object-oriented language, so even functions are objects and have a type, Function.

Apply the null aware ?. operator to the call method of function objects:

typedef void SomeFunc();

SomeFunc f = null;

f?.call();

Answered By – attdona

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *