Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-aware function call? [duplicate]

Tags:

dart

dart-2

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?

like image 765
Eiko Avatar asked Feb 28 '19 19:02

Eiko


People also ask

Is null or empty Dart?

How to Check String is Empty or Not in Dart (Null Safety)? We can check a string is empty or not by the String Property isEmpty. If the string is empty then it returns True if the string is not empty then it returns False. Return : True or False.

IS null safety good?

If you have a value of a nullable type, you can't really do anything useful with it. In cases where the value is null , that restriction is good. It's preventing you from crashing. But if the value isn't null , it would be good to be able to move it over to the non-nullable side so you can call methods on it.

How many null-aware operators in flutter?

The three null-aware operators that Dart provides are ?. , ?? , and ??= .


1 Answers

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();
like image 149
attdona Avatar answered Nov 15 '22 10:11

attdona