在Dart中打包/解包参数

时间:2017-03-16 10:40:12

标签: dart

在Dart中是否有办法在函数中打包/解包参数(例如Python)?

对于打包示例,能够声明如下函数:

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

然后这样做:

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

会显示:

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

至于解包,能够做到这样的事情:

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

相关问题https://github.com/dart-lang/sdk/issues/29087

1 个答案:

答案 0 :(得分:3)

目前不支持此功能,但您可以通过列表和列表轻松打包自己。图:

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