Dart, how to make a function that can take any number of arguments

Starting with python , I know I can easily accomplish this:

 def someFunc(*args): for i in args: print i 

That way I can easily give 100 arguments.

How to do something like this on Dart?

thanks.

+4
source share
2 answers

There is no real vararg support in Dart. It was, but deleted . As Fox32 said, you can do this with noSuchMethod . But, if there is no need to name a method like method(param1, param2, param3) , you can simply skip this step and define the 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}); } 
+9
source

You can use the noSuchMethod method for the class (perhaps in combination with the call() method, but I have not tried this). But it seems that you are losing some of the dart editor checking features when using this (at least for me).

A method has an Invocation instance as a parameter that contains the method name and all unnamed parameters as a list and all named parameters as a hash map.

Read more about noSuchMethod and call() here . But the link contains outdated information that is not relevant to Milestone 4, see here for changes.

Something like that:

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

Using:

 class AClass { final aMethod = new MyFunction((p, n) { for(var a in p) { print(a); } }); } var b = new AClass(); b.aMethod(12, 324, 324); 
+2
source

All Articles