computmaxer
computmaxer

Reputation: 1713

Get a collection of arguments passed to a Dart function/constructor call

I'm essentially looking for the JavaScript arguments functionality but in Dart.

Is this possible in Dart?

Upvotes: 6

Views: 2708

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76223

You have to play with noSuchMethod to do that (see Creating function with variable number of arguments or parameters in Dart)

Either at the class level:

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
}

Or at field level :

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);
}

The second option allows to have code completion for myMethod and avoid a warning.

Upvotes: 7

Related Questions