Null感知函数调用操作符

xst*_*ter 15 nullable dart

我们也可以这样做

nullableClassInstance?.method(blah)
Run Code Online (Sandbox Code Playgroud)

有办法吗?

nullableFunctionInstance?(blah)
Run Code Online (Sandbox Code Playgroud)

换句话说,是否有运算符检查函数实例是否为空,如果是,则在一行中调用函数?

Gan*_*ede 34

使用call方法,您可以实现您想要的:

nullableFunctionInstance?.call(blah)


Nat*_*hat 11

如果您有一个 Function Object ,您可以使用该call方法并将所有参数发送到与调用该函数完全相同的那个。在这里,您可以使用空感知成员访问运算符。

void myFun(int a , int b){...}

var myVar = myFun ;
Run Code Online (Sandbox Code Playgroud)

称呼

函数 myVar 只有在它不为 null 时才会被调用,如下所示。

myVar?.call( arg1 , arg2 );
Run Code Online (Sandbox Code Playgroud)

申请

如果您的函数是动态的,或者您希望控制在运行时调用哪个函数,您可以使用像这样的apply静态方法Function

Function.apply(myVar , [arg1 , arg2]);
Run Code Online (Sandbox Code Playgroud)

apply接受函数和List将被发送到函数的参数。

阅读有关致电申请的更多信息: