使用retainWhere过滤列表时触发NoSuchMethodError问题求助
问题解决:NoSuchMethodError - List无匹配参数的retainWhere方法
错误原因
- retainWhere无orElse参数:Dart的
List.retainWhere方法仅接收测试函数参数,不存在orElse参数,这是触发报错的直接原因。 - retainWhere返回值为void:该方法是原地修改列表,不会返回新列表,不能用变量接收其返回值。
- 逻辑错误:原代码用retainWhere保留匹配项后又添加相同项,会导致重复数据,违背搜索历史去重的需求。
修复后的代码
static Future<List<dynamic>> getSearchHistory() async { final value = await _storage.read(key: _keySearchHistory); // 返回空列表而非null,简化后续逻辑 return value == null ? [] : List.from(json.decode(value)); } static Future setSearchHistory(Map<String, dynamic> history) async { var results = await getSearchHistory(); // 检查搜索历史中是否已存在当前项 bool hasDuplicate = results.any((result) => result['value'].toLowerCase() == history['value'].toString().toLowerCase() ); if (!hasDuplicate) { // 可选:限制搜索历史最多10条,超过则移除最早的记录 if (results.length >= 10) { results.removeAt(0); } results.add(history); final value = json.encode(results); await _storage.write(key: _keySearchHistory, value: value); } }
关键修改点
- 将
getSearchHistory的返回值改为空列表而非null,避免冗余的null判断 - 用
any方法替代错误的retainWhere用法,高效检查重复项 - 移除无效的
orElse参数,符合Dart标准API规范 - 添加可选的历史记录数量限制,优化用户体验
- 修正原逻辑中重复添加数据的问题
内容的提问来源于stack exchange,提问作者Vedha
相关产品推荐
相关产品推荐

