7

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?

Eiko
  • 25,601
  • 15
  • 56
  • 71

1 Answers1

17

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();
attdona
  • 17,196
  • 7
  • 49
  • 60
  • Thank you, this indeed works. From the docs alone, this wasn't clear to me (the "call()" is mentioned only for callable classes. But put together, it makes sense. – Eiko Mar 01 '19 at 08:43
  • You can also use `apply` for this for more control : See https://stackoverflow.com/a/61141239/6665568 – Natesh bhat Apr 10 '20 at 13:27