Flutter集成Cloud Firestore无法新增多条数据,仅更新单条数据
问题原因与解决方案
你的问题出在Firestore的操作逻辑上:你用doc(userId)指定了固定的文档ID,再调用set()方法写入数据。在Firestore中,同一个文档ID的set()操作会直接覆盖原有文档的全部内容,所以每次点击按钮时,你并没有新增记录,只是在更新这条固定ID的文档。
解决方法一:让Firestore自动生成新文档ID(推荐)
把doc(userId).set()替换成add()方法,Firestore会自动为每条新记录生成唯一的文档ID,实现真正的新增记录:
Future addInterventionToDB(String userId, String etat, String op, String iv) { return FirebaseFirestore.instance .collection("interventions") .add({ 'etat': etat, 'operateur': op, 'intervention': iv, 'userId': userId }); }
解决方法二:用子集合归类存储用户的多条记录
如果希望把同一个用户的所有干预记录放在一起管理,可以在用户文档下创建子集合,每条记录都存在对应用户的子集合中:
Future addInterventionToDB(String userId, String etat, String op, String iv) { return FirebaseFirestore.instance .collection("users") .doc(userId) .collection("interventions") .add({ 'etat': etat, 'operateur': op, 'intervention': iv, 'userId': userId }); }
两种方案任选其一即可,UI部分的代码不需要修改,只需要替换数据库操作的方法。
内容的提问来源于stack exchange,提问作者Fedy Belaid
相关产品推荐
相关产品推荐

