Dart中使用retainWhere导致原列表被修改的问题咨询
原交易列表被意外修改的原因及解决方法
问题原因
Dart中的List属于引用类型,当你执行List<trx.Transaction> filteredTrx = transactionList;时,并没有生成新的列表实例,只是让filteredTrx变量指向了和transactionList完全相同的内存对象。
这意味着后续对filteredTrx调用retainWhere方法时,本质上是直接操作原列表的内容——因为两个变量指向的是同一个列表,所以原transactionList的元素会被过滤清空。
解决方案
要避免修改原列表,必须先创建原列表的独立副本,可以通过toList()或List.from()方法实现:
void onItemSelected(String status) { print("default list count: " + transactionList.length.toString()); // 创建原列表的副本,断开引用关联 List<trx.Transaction> filteredTrx = transactionList.toList(); print("default2 list count: " + transactionList.length.toString()); filteredTrx.retainWhere((element) => element.status == status); print("default3 list count: " + transactionList.length.toString()); filteredTransactionList = filteredTrx; }
toList()方法会生成一个包含原列表所有元素的新列表实例,此时filteredTrx和transactionList指向不同的内存对象,对filteredTrx的过滤操作只会影响副本,原列表的内容得以保留。
内容的提问来源于stack exchange,提问作者Chew Hong Yu
相关产品推荐
相关产品推荐

