简体   繁体   中英

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.

 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?

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 :

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. Instead you should call "get" on the DocumentReference first (using "await"), then compare that result to null. If it's null then you should call "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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