【问题标题】:Failing to write data to firestore using flutter and firebase使用flutter和firebase无法将数据写入firestore
【发布时间】:2020-01-26 10:42:26
【问题描述】:

我正在尝试将一些数据写入 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,
        ),
      ),
    );
  }

也许我没有很好地分配 chatRoomId?

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    为了让它工作,我不得不按照 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();
       }
    

    【讨论】:

      【解决方案2】:

      看起来“if”语句中的条件总是为假,因为它将 DocumentReference 对象与 null 进行比较。相反,您应该首先在 DocumentReference 上调用“get”(使用“await”),然后将该结果与 null 进行比较。如果它为空,那么你应该调用“setData”。

      例如:

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

      我也相信应该使用“await”来等待“setData”调用。

      【讨论】:

      • 我试图实现这一点,但我得到以下错误:方法 'getData' 没有为类 'DocumentReference' 定义。尝试将名称更正为现有方法的名称,或定义名为“getData”的方法。
      • 对不起,应该是“get”。我刚刚编辑了我的答案。
      • 好吧,我没有收到任何错误,但集合仍未保存到 firestore...
      • 我有点迷茫,我写数据的时候应该用setData,而不是set(),对吗?
      • 你是对的。我是迷茫的,哈哈。我把它和 Firestore JavaScript 库混在一起了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2020-12-30
      • 2020-07-28
      • 2023-01-04
      相关资源
      最近更新 更多