Reputation: 261
I'm trying to call a function in dart with a set of parameters that is provided in an array. I want to be able to pass the parameters to the function without knowing how many parameters there will be.
Ex:
someFunc(var a, var b, var c) {...}
paramArray = [1,2,3];
callFunction(var func, var params) {
//Here is a sloppy workaround to what I want the functionality to be
switch(params.length) {
case 0:
func()
break;
case 1:
func(params[0])
break;
case 2:
func(params[0], params[1])
break;
...
}
}
callFunction(someFunc, paramArray);
Does there exist a cleaner way to do this in dart without changing the signature of someFunc?
Upvotes: 4
Views: 8121
Reputation: 71693
The Function.apply method does precisely what you want.
You can do Function.apply(func, params)
and it will call func
if the parameters match (and throw if they don't).
Upvotes: 4
Reputation: 1258
I posted a similar question not so long ago : Packing/Unpacking arguments in Dart
Currently not supported but the dart team is aware of this feature. Not their priority though.
Upvotes: 0
Reputation: 721
Not to my knowledge. At this point, Dart doesn't support varargs
. For now, just take an Iterable
as a parameter instead.
Upvotes: 3