You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:45:03