Flutter中向列表的列表添加元素时所有子列表被同步更新的问题
Flutter列表的列表添加子列表被覆盖问题解决
问题原因
Dart里的List是引用类型,你每次调用listOfSelectedDays.add(routineSelectedDays)时,并没有把routineSelectedDays的内容复制进去,而是把这个列表的引用存到了listOfSelectedDays里。后续修改routineSelectedDays的元素时,所有指向这个引用的子列表都会同步变化,看起来就像之前添加的子列表被覆盖了。
解决方案
每次添加时,创建routineSelectedDays的独立副本再加入到listOfSelectedDays中,这样每个子列表都是单独的对象,修改原列表不会影响已添加的子列表。以下是几种常用的创建副本方式:
方式1:用List.from()生成副本
修改添加按钮的代码:
ElevatedButton(onPressed: (){ listOfSelectedDays.add(List.from(routineSelectedDays)); print(listOfSelectedDays); }, child: Text('Add Step')),
方式2:用扩展运算符...快速创建副本
ElevatedButton(onPressed: (){ listOfSelectedDays.add([...routineSelectedDays]); print(listOfSelectedDays); }, child: Text('Add Step')),
方式3:调用列表的toList()方法
ElevatedButton(onPressed: (){ listOfSelectedDays.add(routineSelectedDays.toList()); print(listOfSelectedDays); }, child: Text('Add Step')),
修改后的效果
完成修改后,点击"Add Step"保存当前选择状态,之后再修改日期选择,已存入listOfSelectedDays的子列表不会再被改动。比如第一次添加[true, true, true, true, true, true, true],修改选择后再添加,最终的listOfSelectedDays会显示:
[[true, true, true, true, true, true, true], [false, false, true, true, true, true, true]]
内容的提问来源于stack exchange,提问作者Steven J Reeves
相关产品推荐
相关产品推荐

