Flutter Provider列表变量非预期变更问题求助
Flutter Provider列表状态同步异常解决方法
问题出在列表的引用赋值上——Dart里列表是引用类型,你直接用_savedSelectedFlavorsIndices = _currentSelectedFlavorsIndices这种写法,只是让两个变量指向同一个内存里的列表对象。所以不管你修改_current还是_saved,本质上都是在操作同一个列表,自然会出现未保存就同步变更的情况。
解决办法很简单,每次赋值时创建列表的副本,让两个变量指向不同的对象:
修改你的Provider代码:
List<int> _savedSelectedFlavorsIndices = []; List<int> _currentSelectedFlavorsIndices = []; void updateCurrentSelectedFlavorsIndices(int index) { if (_currentSelectedFlavorsIndices.contains(index)) { _currentSelectedFlavorsIndices.remove(index); } else { _currentSelectedFlavorsIndices.add(index); } notifyListeners(); } void discardCurrentFlavors() { // 创建副本,避免引用同一对象 _currentSelectedFlavorsIndices = List.from(_savedSelectedFlavorsIndices); notifyListeners(); } void updateSavedIndices() { // 创建副本,保存当前选择的独立快照 _savedSelectedFlavorsIndices = [..._currentSelectedFlavorsIndices]; }
原理说明
List.from(list)或者扩展运算符[...list]都会创建一个新的列表对象,把原列表的元素复制进去- 这样
_saved和_current就各自持有独立的列表,修改其中一个不会影响另一个 - 只有调用
updateSavedIndices时,_saved才会更新为当前选择的副本;调用discardCurrentFlavors时,_current会重置为_saved的副本
测试一下:修改当前选项但不保存,此时_saved不会跟着变;点击保存后,_saved才同步当前选择;点击丢弃,当前列表会回到最近一次保存的状态。
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

