Coming from python
, i know i can easily accomplish that :
def someFunc(*args):
for i in args:
print i
That way i can give 100 args with ease.
How to do something like that on Dart ?
Thx.
So if you'd like to make a function that accepts any number of positional arguments, use the * operator.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
Dart has three ways to declare parameters for a function. Required positional parameters. Named parameters. Optional positional parameters.
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});
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With