Flutter中筛选API返回的docStatus为Open的文档列表用于下拉选择
如何在Flutter中正确筛选API返回的docStatus为"Open"的文档列表
问题背景
在Flutter开发中,我需要将API返回的同类数据存入变量,用于后续下拉选择功能。API返回的JSON数据如下:
[{ "docId": 1053, "tokenNo": 23477779999999, "docTitle": "Karishma resort ,baner", "address": "baner", "city": "pune", "partyName": "Rajesh patil", "pinCode": "452899", "docType": "Commercial", "duration": "24", "startDate": "2023-01-11", "endDate": "2025-01-10", "docStatus": "Open", "rentDesc": "17000", "createdBy": "Vaishnavi", "updatedBy": "null" }, { "docId": 1052, "tokenNo": 22010799911122, "docTitle": "swapnapurti heights", "address": "Pirangut", "city": "Pune", "partyName": "Pranjali Sul", "pinCode": "411033", "docType": "Residential", "duration": "12", "startDate": "2023-01-07", "endDate": "2024-01-06", "docStatus": "Open", "rentDesc": "", "createdBy": "", "updatedBy": "" }, { "docId": 1050, "tokenNo": 72389572857572, "docTitle": "Krishna Murti Nivas", "address": "Bavdhan", "city": "pune", "partyName": "Suhas kale", "pinCode": "736476", "docType": "Residential", "duration": "24", "startDate": "2023-01-14", "endDate": "2025-01-13", "docStatus": "Open", "rentDesc": "87033", "createdBy": "null", "updatedBy": "null" }, { "docId": 932, "tokenNo": 2212010909755, "docTitle": "6/10 B Digital Apartment", "address": "Kothrud", "city": "Pune", "partyName": "Suresh", "pinCode": "411112", "docType": "Residential", "duration": "11", "startDate": "2022-12-01", "endDate": "2023-12-01", "docStatus": "Open", "rentDesc": "5000", "createdBy": "Swati", "updatedBy": null }]
我尝试用以下代码获取docStatus为"Open"的文档,但逻辑存在问题:
List<Document> docs = []; openedDocs() async { final docs = await DocumentController.getdocs(value); List<Document> opened; for (int i = 0; i <= docs.length; i++) { docs[i].docStatus == "Open" ? this.docs = docs : this.docs = List.empty(); } }
API调用的getdocs方法实现如下:
static Future<List<Document>> getdocs(String query) async { await SharedPrefService.init(); var AuthToken = SharedPrefService.pref.getString('authToken'); final url = Uri.parse('http://192.168.0.131:8080/AtdochubJ-3/document/'); final response = await http.get(url, headers: { HttpHeaders.authorizationHeader: '${AuthToken}', 'Content-Type': 'application/json; charset=UTF-8', }); if (response.statusCode == 200) { final List docs = json.decode(response.body); return docs.map((json) => Document.fromJson(json)).where((doc) { final titleLower = doc.docTitle.toLowerCase(); final tokenLower = doc.tokenNo.toString(); final searchLower = query.toLowerCase(); return titleLower.contains(searchLower) || tokenLower.contains(searchLower); }).toList(); } else { throw Exception(); } }
需要解决如何正确获取所有docStatus为"Open"的文档列表。
解决方案
当前openedDocs方法存在两个核心问题:
- 循环条件错误:
i <= docs.length会触发数组越界异常,正确的条件应该是i < docs.length - 筛选逻辑错误:每次循环直接替换整个
this.docs变量,无法累积符合条件的文档
可以通过以下两种方式实现正确筛选:
方式一:在openedDocs中直接筛选
利用Dart内置的where方法过滤列表,代码简洁高效:
List<Document> docs = []; openedDocs() async { final fetchedDocs = await DocumentController.getdocs(value); // 筛选出所有docStatus为"Open"的文档 this.docs = fetchedDocs.where((doc) => doc.docStatus == "Open").toList(); }
方式二:在API请求方法中同时处理搜索和状态筛选
如果希望API返回的结果直接满足搜索条件且状态为"Open",可以修改getdocs的过滤逻辑:
static Future<List<Document>> getdocs(String query) async { await SharedPrefService.init(); var AuthToken = SharedPrefService.pref.getString('authToken'); final url = Uri.parse('http://192.168.0.131:8080/AtdochubJ-3/document/'); final response = await http.get(url, headers: { HttpHeaders.authorizationHeader: '${AuthToken}', 'Content-Type': 'application/json; charset=UTF-8', }); if (response.statusCode == 200) { final List docs = json.decode(response.body); return docs.map((json) => Document.fromJson(json)).where((doc) { final titleLower = doc.docTitle.toLowerCase(); final tokenLower = doc.tokenNo.toString(); final searchLower = query.toLowerCase(); // 同时满足搜索条件和状态为Open return (titleLower.contains(searchLower) || tokenLower.contains(searchLower)) && doc.docStatus == "Open"; }).toList(); } else { throw Exception('Failed to fetch documents'); } }
修改后,openedDocs可以简化为:
List<Document> docs = []; openedDocs() async { this.docs = await DocumentController.getdocs(value); }
额外注意事项
- 确保字符串匹配一致:API返回的
docStatus是"Open",判断时要完全匹配大小写;如果存在大小写不一致的可能,可以用doc.docStatus?.toLowerCase() == "open"兼容 - 处理空值情况:如果
docStatus字段可能为null,需要添加空值判断避免异常
内容的提问来源于stack exchange,提问作者Minal Suryawanshi
相关产品推荐
相关产品推荐

