Flutter开发报错:Stream类型未定义doc方法,聊天应用功能异常
问题解决:The method 'doc' isn't defined for the type 'Stream'
错误原因
你调用了.snapshots()方法,它返回的是**Streamdoc()是CollectionReference类的专属方法,Stream没有这个方法,因此触发报错。.snapshots()用于监听集合数据的实时变化,而你当前的需求是写入数据,完全不需要这个监听操作。
修复后的代码
static Future<void> sendmessages(chatusres chuser, String msg) async { final time = DateTime.now().millisecondsSinceEpoch.toString(); final Messeges messeges = Messeges( fromid: user.uid, msg: msg, read: '', sent: time, toid: chuser.id, type: ''); // 移除.snapshots(),直接获取集合引用 final ref = firestore .collection('chats/${getconversationid(user.uid)}/messages'); await ref.doc(time).set(messeges.toJson()); }
额外提示
- 原代码中集合路径末尾多了一个多余的闭合大括号
},修复时已一并移除,避免因路径错误导致后续问题 - 如果之后需要监听消息集合的实时更新,再在集合引用上调用
.snapshots(),示例代码如下:firestore.collection('chats/目标会话ID/messages').snapshots().listen((snapshot) { // 处理实时更新的消息数据 });
内容的提问来源于stack exchange,提问作者Vinay Chavhan
相关产品推荐
相关产品推荐

