Dart how to make a function that can accept any number of args
You can use the noSuchMethod
method on a class (Probably in combination with the call()
method, but i haven't tried that). But it seems like you loose some checking features of the dart editor when using this (at least for me).
The method has a Invocation
instance as a parameter that contains the method name and all unnamed parameters as a list and all named parameters as a hashmap.
See here for more details about noSuchMethod
and call()
. But the link contains outdated informations that do not apply for Milestone 4, see here for the changes.
Something like this:
typedef dynamic FunctionWithArguments(List<dynamic> positionalArguments, Map<Symbol, dynamic> namedArguments);
class MyFunction
{
final FunctionWithArguments function;
MyFunction(this.function);
dynamic noSuchMethod(Invocation invocation) {
if(invocation.isMethod && invocation.memberName == const Symbol('call')) {
return function(invocation.positionalArguments, invocation.namedArguments);
}
return;
}
}
Usage:
class AClass {
final aMethod = new MyFunction((p, n) {
for(var a in p) {
print(a);
}
});
}
var b = new AClass();
b.aMethod(12, 324, 324);
There is no real vararg support in Dart. There was, but it has been removed. As Fox32 said, you can do this with noSuchMethod
. But, if there is no real need to call the method like method(param1, param2, param3)
, you could just skip this step and define a Map
or List
as parameter. Dart supports literals for both types, so the syntax is also short and clear:
void method1(List params) {
params.forEach((value) => print(value));
}
void method2(Map params) {
params.forEach((key, value) => print("$key -- $value"));
}
void main() {
method1(["hello", "world", 123]);
method2({"name":"John","someNumber":4711});
}