4

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?

user1497256
  • 241
  • 1
  • 3
  • 4

3 Answers3

4

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).

lrn
  • 64,680
  • 7
  • 105
  • 121
3

Not to my knowledge. At this point, Dart doesn't support varargs. For now, just take an Iterable as a parameter instead.

Tobe Osakwe
  • 729
  • 7
  • 18
0

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.

Community
  • 1
  • 1
aelayeb
  • 1,208
  • 2
  • 9
  • 11