Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function with an array of parameters in Dart

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?

like image 989
user1497256 Avatar asked Oct 27 '25 12:10

user1497256


1 Answers

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

like image 182
lrn Avatar answered Oct 30 '25 05:10

lrn