Flutter:如何更改循环中创建的开关的值?

发布于 2025-01-20 06:52:15 字数 744 浏览 2 评论 0原文

本质上,我在重写的 buildState 方法中以这种方式创建了开关:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文