Flutter Dart中实现类似LINQ的where select语法及空类型报错解决
问题原因
报错<type 'Null' is not a subtype of type 'int'核心是你给要求非空int的参数传了空值,再加上你代码里还有字段不匹配、类型不匹配的问题,具体触发点:
- 从Map取
unitId/CUSTOMERID等字段时,key不存在或者对应值为空,直接赋值给非空int参数 - 后端要求
CustomerId是int类型,你调用了toString()转成字符串提交,类型不匹配 - 明细字段名和后端定义不一致:后端字段是
receiptDetails,你提交的key是OrderDetails,后端无法正常解析 map操作后没有调用toList(),提交的是Iterable类型而非要求的List类型
正确实现代码
// 提前提取公共值避免重复读取,同时做空判断 final firstReceipt = receipt.firstOrNull; if (firstReceipt == null) { // 自行处理receipt为空的边界逻辑 return; } // 转换CustomerId为int类型,做空校验 final customerId = int.tryParse(firstReceipt['CUSTOMERID']?.toString() ?? ''); if (customerId == null) { // 自行处理客户ID格式错误/为空的边界逻辑 return; } // 实现类似LINQ的筛选+转换逻辑,全链路空值处理 final validReceiptDetails = receiptDetailItem // 先过滤掉为空的元素 .where((element) => element != null) // 按LOCALRECEIPTID筛选 .where((element) => element["LOCALRECEIPTID"] == firstReceipt['LOCALRECEIPTID']) .toSet() .toList() // 转换为后端要求的ReceiptDetailItem格式,做空值校验 .map((e) { final unitId = int.tryParse(e["unitId"]?.toString() ?? ''); final amount = double.tryParse(e["amount"]?.toString() ?? ''); // 过滤掉字段不完整的无效明细 if (unitId == null || amount == null) return null; return ReceiptDetailItem( unitId: unitId, amount: amount, ); }) // 去掉空的无效项,最后转成List .whereType<ReceiptDetailItem>() .toList(); // 提交请求 await generalService.POSTAPI( url: "POSTMyItem", body: { "CustomerId": customerId, "Desc": firstReceipt['DESC']?.toString() ?? '', "receiptDetails": validReceiptDetails, }, ).then((value) async { // 原有后续逻辑 });
注意事项
- 提交的字段名必须和后端C#类的属性名完全一致,大小写也要对齐
- 所有从动态Map中取的字段都要做空校验,不要直接用
as int这种强转方式,优先用tryParse做安全转换 - 筛选、转换操作完成后必须调用
toList()才能生成List类型的集合
内容的提问来源于stack exchange,提问作者Aurora
相关产品推荐
相关产品推荐

