Flutter/Dart:过滤Map列表时出现NoSuchMethodError的解决方法
Flutter预约列表过滤错误修复方案
问题场景
你有如下静态预约列表:
static final appointments = [ { "status": "Upcoming", "doctor": { "name": "Dr Mahdi CHAKROUN", "image": "lib/assets/images/doctor3.png", "specialist": "Cardiologue" }, "date": "16 july, 2021", }, { "status": "Upcoming", "doctor": { "name": "Dr Leila Riahi", "image": "lib/assets/images/doctor2.png", "specialist": "Cardiologue" }, "date": "16 july, 2021", }, { "status": "Past", "doctor": { "name": "Dr Mahdi CHAKROUN", "image": "lib/assets/images/doctor3.png", "specialist": "Cardiologue" }, "date": "10 july, 2021", }, { "status": "Past", "doctor": { "name": "Dr Mahdi CHAKROUN", "image": "lib/assets/images/doctor.png", "specialist": "Orthodontist" }, "date": "10 july, 2021", }, ];
尝试按选中类型(Incoming/Past)过滤列表时,编写了如下代码:
class _BodyState extends State<Body> { String _selectedAppointments = "Incoming"; List<Map<String, Object>?> selectedAppointmentsList = Constants.appointments.map((appointment) { if (appointment["status"] == "Past") { return appointment; } }).toList();
运行时出现错误:
The following NoSuchMethodError was thrown building:
The method '[]' was called on null.
Receiver: null
Tried calling: []
错误原因
- 使用
map方法过滤时,不满足条件的元素会返回null,最终列表中混入null值,后续UI渲染访问null["xxx"]时触发报错。 - 选中状态字符串不匹配:代码中
_selectedAppointments初始值是"Incoming",但静态列表中对应的状态是"Upcoming",会导致初始过滤逻辑完全失效。
修复方案
1. 替换过滤方法:用where替代map
where会直接筛选符合条件的元素,不会保留null,返回的列表无空值,避免后续访问错误。
2. 统一状态匹配字符串
将_selectedAppointments的初始值改为和静态列表一致的"Upcoming",或在过滤逻辑中做对应映射。
3. 优化代码结构(可选)
将过滤逻辑封装为方法,方便切换选中类型时更新列表。
修正后的完整代码示例:
class _BodyState extends State<Body> { String _selectedAppointments = "Upcoming"; // 匹配静态列表中的状态值 List<Map<String, Object>> selectedAppointmentsList = []; @override void initState() { super.initState(); _filterAppointments(); // 初始化时执行过滤 } // 过滤预约列表的方法 void _filterAppointments() { setState(() { selectedAppointmentsList = Constants.appointments.where((appointment) { if (_selectedAppointments == "Upcoming") { return appointment["status"] == "Upcoming"; } else { return appointment["status"] == "Past"; } }).toList(); }); } // 切换预约类型的方法(示例) void _onAppointmentTypeChanged(String newType) { setState(() { _selectedAppointments = newType; _filterAppointments(); }); } @override Widget build(BuildContext context) { // 后续UI渲染使用selectedAppointmentsList即可,无需担心null问题 return ...; } }
内容的提问来源于stack exchange,提问作者Idriss Garfa
相关产品推荐
相关产品推荐

