Flutter对接FirebaseFirestore报错:Object类型未定义forEach方法如何解决?
问题修复方案
错误原因
The method 'forEach' isn't defined for the type 'Object'. Try correcting the name to the name of an existing method, or defining a method named 'forEach'.
该报错是因为高版本cloud_firestore插件中,DocumentSnapshot.data()方法默认返回Object?类型,Dart无法自动识别它实际是存储数据的Map<String, dynamic>结构,因此判定Object类型没有forEach方法,抛出异常。
修复方法
只需要在调用forEach前,将value.data()显式转换为Map<String, dynamic>类型即可,修改getData()方法的逻辑:
getData() async { await linkRef .get() .then((value) { // 新增显式类型转换逻辑 final data = value.data() as Map<String, dynamic>?; data?.forEach((key, value) { if (!videoID.contains(value)) { videoID.add(value); } }); }) .whenComplete(() => setState(() { videoID.shuffle(); showItem = true; })); }
内容的提问来源于stack exchange,提问作者Chatchai Suriyon
相关产品推荐
相关产品推荐

