Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null aware function invocation operator

Tags:

nullable

dart

In the same way we can have

nullableClassInstance?.method(blah) 

Is there a way to do

nullableFunctionInstance?(blah) 

In other words, is there an operator that checks whether a function instance is not null, if so, invoke the function all in one line?

like image 754
xster Avatar asked Jul 10 '17 21:07

xster


People also ask

What is null-aware operators?

Null-aware operators are used in almost every programming language to check whether the given variable value is Null. The keyword for Null in the programming language Dart is null. Null means a variable which has no values assign ever and the variable is initialized with nothing like.

How many null-aware operators in flutter?

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

How do you use the null check operator in flutter?

Use the fallback operator to set a default value for null values before using the variable. Here, "str" is null, and we set the fallback operator with fallback value in case of "str" is null. You need to do this before using it on the code.

How do you use null safety in darts?

Null Safety in simple words means a variable cannot contain a 'null' value unless you initialized with null to that variable. With null safety, all the runtime null-dereference errors will now be shown in compile time. String name = null ; // This means the variable name has a null value.


2 Answers

Using the call method, you can achieve what you want with:

nullableFunctionInstance?.call(blah) 

There's also the apply method if you want to pass arguments.

like image 155
Ganymede Avatar answered Oct 08 '22 04:10

Ganymede


If you have a Function Object , you can use the call method and send all the parameters to that which works exactly as calling the function. Here , you can use the null aware member access operator.

void myFun(int a , int b){...}  var myVar = myFun ; 

call

The function myVar will only get called if its not null as shown below.

myVar?.call( arg1 , arg2 ); 

apply

If your function is dynamic or you wish to control which function is being called at run time , you can use the apply static method of Function like so :

Function.apply(myVar , [arg1 , arg2]); 

apply takes the function and a List of parameters that will be sent to the function.

Read more about call and apply :

like image 21
Natesh bhat Avatar answered Oct 08 '22 06:10

Natesh bhat