Flutter:如何更改循环中创建的开关的值?
本质上,我在重写的 build
的 State
方法中以这种方式创建了开关:
List<Switch> daySwitches = [];
for (int i = 0; i <= 6; i++) {
daySwitches.add(Switch(
(...)
onChanged: (bool value) {
days[i].active = value;
},
(...)
value: days[i].active,
));
之后,daySwitches
的内容添加到构建方法,这样:
return Column(children: daySwitches);
问题是,当我单击一个 Switch
时,其中任何一个都完全改变了。当我在 onChanged
中放置断点时,我看到变量 i
具有正确的值,而且还看到每个变量的所有 active
字段在执行这唯一一行代码的过程中,日子确实完全改变了。
为什么会出现这种情况?是因为我使用了临时变量(daySwitches
)吗?我真的应该使用像 return Column(children: days.forEach(...).toList();
这样的东西吗?
In essence, I have the switches created this way within an overridden build
's State
method:
List<Switch> daySwitches = [];
for (int i = 0; i <= 6; i++) {
daySwitches.add(Switch(
(...)
onChanged: (bool value) {
days[i].active = value;
},
(...)
value: days[i].active,
));
After that, the content of daySwitches
is added in athe build method, this way:
return Column(children: daySwitches);
The problem is that when I click on one Switch
, any of them, there all changed altogether. When I put a breakpoint in onChanged
, I see that the variable i
has the right value, but also see that all the active
fields of each day are really changed altogether during the execution of this only line of code.
Why does this happen? Is it because I use a temporary variable (daySwitches
)? Should I really use something like return Column(children: days.forEach(...).toList();
, or so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论