获取传递给Dart函数/构造函数调用的参数集合

com*_*xer 4 dart

我本质上是在寻找JavaScriptarguments功能,但在Dart中.

这在Dart有可能吗?

Ale*_*uin 6

您必须使用它noSuchMethod来执行此操作(请参阅在Dart中使用可变数量的参数或参数创建函数)

在班级:

class A {
  noSuchMethod(Invocation i) {
    if (i.isMethod && i.memberName == #myMethod){
      print(i.positionalArguments);
    }
  }
}

main() {
  var a = new A();
  a.myMethod(1, 2, 3);  // no completion and a warning
}
Run Code Online (Sandbox Code Playgroud)

或者在现场级别:

typedef dynamic OnCall(List l);

class VarargsFunction extends Function {
  OnCall _onCall;

  VarargsFunction(this._onCall);

  call() => _onCall([]);

  noSuchMethod(Invocation invocation) {
    final arguments = invocation.positionalArguments;
    return _onCall(arguments);
  }
}

class A {
  final myMethod = new VarargsFunction((arguments) => print(arguments));
}

main() {
  var a = new A();
  a.myMethod(1, 2, 3);
}
Run Code Online (Sandbox Code Playgroud)

第二个选项允许代码完成myMethod并避免警告.