使用flutter和firestore创建文档时如何存储文档ID

我正在创建一个 Todo 应用程序,我需要访问存储在 firestore 中的文档的 ID 才能删除它们。但是我在创建它时不知道如何保存它。这是我添加屏幕中创建新文档的部分。

 _firestore.collection('todos').add({
                    'title' : title,
                    'type' : type,
                    'date' : dayDate,
                    'time' : _dayTime,
                    'category' : category,
                    'author' : loggedInUser.uid,
                    //'id' : doc.id
                  
                  });

我不知道如何访问它。而且我将我的任务显示到卡片中,当我长按它们时,我希望它们从 firestore 中删除,但我不能,因为我不知道他们的想法。这是我的空函数:

void deleteTask(){
_firestore.collection("todos").doc().delete();
}

如果您有任何想法,请告诉我。谢谢你们!

回答

您可以先获取文档 ID,CollectionRef.pots.doc().id然后再添加它。这样,您将在文档中也有 docId,当您拥有文档数据时,您可以访问该文档。

 static createPot(String name, String password) async{
    try{
      PotModel newPot = PotModel(
        name: name,
        potId: FirebaseFirestore.instance.collection('pots').doc().id, // will generate a random doc id, which will be used to create the next document
        password: password,
        ownerId: ViewModelUser.user.value.mobile,
        createdAt: Timestamp.now(),
        isActive: true,
        potActions: [],
        users: [ViewModelUser.user.value.mobile]
      );
      /// creating a new pot
      DocumentReference documentReference = await FirebaseFirestore.instance.collection('pots').add(newPot.toJson());

      return newPot;
    }catch(e){
      print(e.toString());
      return null;
    }
  }


以上是使用flutter和firestore创建文档时如何存储文档ID的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>