Flutter提供程序列表变量在不应更改时更改

uqdfh47h  于 2023-06-30  发布在  Flutter
关注(0)|答案(1)|浏览(192)

我正在使用Flutter Provider跨不同屏幕管理状态,我遇到了一些Provider类列表变量的问题。我有一个小部件,允许用户从列表中选择/取消选择不同的选项,这将从我的提供程序类列表中添加/删除选定/未选定的索引。我试图实现一个功能,允许保存和丢弃当前选择的选项。当我第一次保存或丢弃当前选择的索引时,一切都很完美,保存的索引相应地更新/不更新,但当我试图修改这些初始选择时,每当我的当前选择的索引列表更新时,我的保存选择的索引列表都会更新,甚至在丢弃或保存之前。
我将只张贴相关的提供程序类代码的小部件代码是很多,但如果需要也将张贴。

  1. List<int> _savedSelectedFlavorsIndices = [];
  2. List<int> _currentSelectedFlavorsIndices = [];
  3. void updateCurrentSelectedFlavorsIndices(int index) {
  4. if (_currentSelectedFlavorsIndices.contains(index)) {
  5. _currentSelectedFlavorsIndices.remove(index);
  6. } else {
  7. _currentSelectedFlavorsIndices.add(index);
  8. }
  9. notifyListeners();
  10. }
  11. void discardCurrentFlavors() {
  12. _currentSelectedFlavorsIndices = _savedSelectedFlavorsIndices;
  13. notifyListeners();
  14. }
  15. void updateSavedIndices() {
  16. _savedSelectedFlavorsIndices = _currentSelectedFlavorsIndices;
  17. }
o2gm4chl

o2gm4chl1#

问题不是来自Provider。这是dart中List的正常行为。你用相同的地址设置它们。
当你称之为:_currentSelectedFlavorsIndices = _savedSelectedFlavorsIndices,这意味着它们现在相同。
我想你想设置所有的值从savedListcurrentList

解决方案:使用List.from()

  1. void discardCurrentFlavors() {
  2. _currentSelectedFlavorsIndices = List.from(_savedSelectedFlavorsIndices);
  3. notifyListeners();
  4. }

  1. void updateSavedIndices() {
  2. _savedSelectedFlavorsIndices = List.from(_currentSelectedFlavorsIndices);
  3. }

希望这能帮上忙。

展开查看全部

相关问题