gpt4 book ai didi

flutter - 将多个函数调用/设置变量全部放在一行中

转载 作者:IT王子 更新时间:2023-10-29 07:08:52 26 4
gpt4 key购买 nike

我需要在函数开始时清除一些列表,否则它们只会通过 add 方法变得越来越大,所以我可以使用 = [].clear() 来实现这一点,但格式将它们全部放在单独的行上,如下所示:

listone.clear();
listtwo.clear();
three.clear();
listfour.clear();
listfive.clear();
listsix.clear();

我想做这样的事情,但它不允许:

listone.clear(), listtwo.clear(), three.clear(), listfour.clear(), listfive.clear(), listsix.clear();

listone = [], listtwo = [], three = [], listfour = [], listfive = [], listsix = [];

如何在同一行中设置多个已声明的变量?

最佳答案

让复杂的东西适应更小空间的最简单方法是使用辅助方法。

clearAll(Iterable<List<Object>> lists) {
for (var list in lists) list.clear();
}

然后你就写:

clearAll([listone, listtwo, three, listfour, listfive, listsix]);

你可以内联辅助函数

for (var l in [listone, listtwo, three, listfour, listfive, listsix]) l.clear();

但无论如何它可能无法放在一行中。

如果您正在设置变量,并且将变量设置为相同的值,那么您可以将多个赋值作为单个表达式:

listone = listtwo = three = listfour = listfive = listsix = [];

不真正推荐用于列表,因为那样所有变量都将指向相同列表对象。它在分配 null 或其他不可变值时效果更好。它也不是特别可读

在 Dart 中没有简单的方法可以在没有帮助的情况下在单个语句中执行多个表达式。

你可以声明:

void do6(void v1, void v2, void v3, void v4, void v5, void v6) {}
...
do6(listone.clear(), listtwo.clear(), three.clear(),
listfour.clear(), listfive.clear(), listsix.clear());

但您可能会发现它也会在不止一行上进行格式化

或者,只需使用列表文字而不是函数参数列表来允许多个表达式:

[listone.clear(), listtwo.clear(), three.clear(), 
listfour.clear(), listfive.clear(), listsix.clear()];

关于长度和格式的相同警告,创建列表然后不使用会造成困惑和低效。

总而言之,请不要试图巧妙地设置格式。只需编写惯用的代码,您的读者将更容易理解它,编译器也会更高效。

关于flutter - 将多个函数调用/设置变量全部放在一行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com