Dart/Flutter遍历Map匹配List字段时接口重复调用异常问题
问题根源
- 嵌套循环的判断逻辑错误:你当前的逻辑是每遍历一个
answerTable的元素,就对当前finalMap的key做一次判断,而不是先判断整个answerTable中是否存在匹配的sectionItemId。比如finalMap的key为17时,遍历第一个answerTable元素匹配到17触发edit,遍历第二个元素sectionItemId为16时不匹配,就会额外触发一次create。 - 匹配成功后没有跳出循环:就算匹配到了对应的
sectionItemId,循环还会继续遍历answerTable剩余的元素,每遇到不匹配的元素都会触发一次create。
修复方案
优先提取answerTable中所有的sectionItemId存入Set集合,遍历finalMap时直接判断key是否在集合中即可,既避免重复遍历,也不会出现误触发的问题,修复后代码如下:
Future editChecklistAnswer( String id, String checklistAnswerId, Map<String, String> textMap) async { List<ChecklistAnswerItem> answerTable = await _repository.selectChecklistAnswerItemsList(); print(finalMap); print(answerTable); // 提前提取所有已存在的sectionItemId字符串集合,用于快速判断 final existSectionIdSet = answerTable .map((item) => item.sectionItemId.toString()) .toSet(); for (final entry in finalMap.entries) { final currentKey = entry.key.toString(); if (existSectionIdSet.contains(currentKey)) { print("edit " + currentKey); // 此处为edit接口调用逻辑 } else { print("create " + currentKey); // 此处为create接口调用逻辑 } } }
该方案的优势:
- 逻辑清晰,仅做一次集合提取,后续判断不会重复触发接口调用
- Set的
contains查询时间复杂度为O(1),answerTable数据量较大时性能远高于嵌套循环遍历
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

