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

Flutter开发中Cloud Firestore新增文档未出现在查询结果中问题求解

Cloud Firestore结构详情
Cloud Firestore控制台截图
Cloud Firestore文档拉取代码
更多详情

我在Flutter项目中使用Cloud Firestore实现聊天消息存储功能,初始发送消息代码如下:

void onSendMessage(String content) {
  
  if (content.trim() != '') {
    textEditingController.clear();
    var documentReference = FirebaseFirestore.instance
        .collection('messages')
        .doc(widget.comid)
        .collection(widget.comid)
        .doc(DateTime.now().millisecondsSinceEpoch.toString());

    FirebaseFirestore.instance.runTransaction((transaction) async {
      transaction.set(
        documentReference,
        {
          'idFrom': widget.userid,
          'idTo': widget.peerid,
          'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
          'content': content,
          
        },
      );
    });
  }
  else {
    Fluttertoast.showToast(
      msg: 'Nothing to send', 
      backgroundColor: Colors.black, 
      textColor: Colors.grey[100]
    );
  }
}

我尝试拉取messages集合下的文档ID,但查询结果为空;但我在Firestore控制台手动添加名为"Anakans"的文档后,该文档可以正常出现在查询结果中。我是Flutter和Firestore开发新手,烦请各位帮忙排查错误。

问题已解决

问题原因是我仅写入了widget.comid文档下的子集合数据,父级widget.comid文档属于不存在的虚拟父文档,无法被集合查询命中。我调整了实现逻辑,在发送消息时同时将最新消息内容写入父级widget.comid文档,父级文档变为真实存在的实体后即可正常拉取到文档ID列表。调整后的onSendMessage函数代码如下:

void onSendMessage(String content) {
  if (content.trim() != '') {
    textEditingController.clear();

    var msg = {
      'idFrom': widget.userid,
      'idTo': widget.peerid,
      'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
      'content': content,
    };

    FirebaseFirestore.instance
        .collection('messages')
        .doc(widget.comid)
        .set(msg);

    var documentReference = FirebaseFirestore.instance
        .collection('messages')
        .doc(widget.comid)
        .collection(widget.comid)
        .doc(DateTime.now().millisecondsSinceEpoch.toString());

    FirebaseFirestore.instance.runTransaction((transaction) async {
      transaction.set(
        documentReference,
        {
          'idFrom': widget.userid,
          'idTo': widget.peerid,
          'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
          'content': content,
        },
      );
    });
  } else {
    Fluttertoast.showToast(
        msg: 'Nothing to send',
        backgroundColor: Colors.black,
        textColor: Colors.grey[100]);
  }
}

内容的提问来源于stack exchange,提问作者Ankan Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:27:04