7

Is there a way in Dart to pack/unpack arguments in a function (like Python for example) ?

For packing example, being able to declare a function like this :

packArguments(*listOfArguments, **mapOfArguments) {
    listOfArguments.forEach((arg) => print(arg));
    mapOfArguments.forEach((key, val) => print("$key => $val"));
}

And then doing this :

packArguments("I", "Put", "whatever", "I", "want, arg1: "A", arg2: 1);

Would display :

I
Put
whatever
I
want
arg1 => A
arg2 => 1

As for unpacking, being able to do something like that :

functionWithLotOfArgument(a, b, c, d, e, {aa, bb = null, cc = null}) {
  // do stuff
}
var argList = [1, 2, 3, 4, 5];
var argMap = {"aa": "haha", bb: "baby"};

functionWithLotOfArgument(*argList, **argMap);

Related issue https://github.com/dart-lang/sdk/issues/29087

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
aelayeb
  • 1,208
  • 2
  • 9
  • 11
  • 1
    Currently not supported. – Günter Zöchbauer Mar 16 '17 at 10:50
  • "Currently" means it's planned ? It would really be nice to have this feature, especially when using Flutter where methods can have a lot of parameters. – aelayeb Mar 16 '17 at 10:53
  • I don't think it's planned, but they are working on more broader changes and something like that might be considered later. You can check the issues https://github.com/dart-lang/sdk/issues. I guess most features one can think of were already suggested at least once ;-) – Günter Zöchbauer Mar 16 '17 at 10:55
  • Ok thank you ! I'll check that. – aelayeb Mar 16 '17 at 10:59

1 Answers1

6

This is not currently supported, but you can very easily pack yourself, by passing a list & map:

void packArguments(List listOfArguments, Map mapOfArguments) {
    listOfArguments.forEach((arg) => print(arg));
    mapOfArguments.forEach((key, val) => print("$key => $val"));
}

void main() {
  packArguments(['a', 3], {'arg1': 'a', 'arg2': 5});
}

https://dartpad.dartlang.org/98ed3a3b07a2cca049cde69ca50ca269

rkj
  • 8,787
  • 2
  • 29
  • 35