简体   繁体   English

无法使用flutter和firebase将数据写入firestore

[英]Failing to write data to firestore using flutter and firebase

I am trying to write some data into firestore, more exactly, a collection containing a document that has a few fields but for some reason it fails.我正在尝试将一些数据写入 firestore,更准确地说,是一个包含具有几个字段但由于某种原因失败的文档的集合。

 void createChatRoom() async {
    instructorUID = (await FirebaseAuth.instance.currentUser()).uid;
    chatRoomID = clientUID + instructorUID;

    if(db.collection('chatrooms').document(chatRoomID) == null) {
      db.collection('chatrooms').document(chatRoomID).setData({
        'instructor': instructorUID,
        'instructorName': widget.name,
        'client': clientUID,
        'clientPhoneNo': clientPhoneNo,
        'createdAt': Timestamp.now(),
      });
    }

    Navigator.push(
      context, 
      MaterialPageRoute(
        builder: (context) => ChatPage(
          chatRoomID: chatRoomID,
          clientUID: clientUID,
        ),
      ),
    );
  }

Maybe I am not assigning the chatRoomId well?也许我没有很好地分配 chatRoomId?

In order to make it work, I had to rewrite the if statement as Richard suggested and make a method for saving data in order to use aynchronous programming as intended :为了使它工作,我不得不按照 Richard 的建议重写 if 语句,并制定一种保存数据的方法,以便按预期使用异步编程:

void saveData() async {
    await db.collection('instructori').document(instructorUID).collection('chatrooms').document(chatRoomID).setData({
        'instructor': instructorUID,
        'instructorName': widget.name,
        'clientPhoneNo': clientPhoneNo,
        'client': clientUID,
        'createdAt': FieldValue.serverTimestamp(),
      });
  }

void createChatRoom() async {
   instructorUID = (await FirebaseAuth.instance.currentUser()).uid;
   chatRoomID = "test";

   if(await db.collection('instructori').document(instructorUID).collection('chatrooms').document(chatRoomID).get() == null)
   {
      print(instructorUID);
      saveData();
   }

It looks like the condition in your "if" statement will always be false, since it's comparing a DocumentReference object to null.看起来“if”语句中的条件总是假的,因为它将 DocumentReference 对象与 null 进行比较。 Instead you should call "get" on the DocumentReference first (using "await"), then compare that result to null.相反,您应该首先在 DocumentReference 上调用“get”(使用“await”),然后将该结果与 null 进行比较。 If it's null then you should call "setData".如果它为空,那么你应该调用“setData”。

For example:例如:

if(await db.collection('chatrooms').document(chatRoomID).get() == null)

Also I believe "await" should be used to wait on the "setData" call.另外我相信“await”应该用于等待“setData”调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM