首页 > 解决方案 > 使用flutter和firestore创建文档ID时如何存储文档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 中删除,但我不能 bc 我没有他们的想法。这是我的空函数:

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

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

标签: flutterdartgoogle-cloud-firestore

解决方案


您可以先获取文档 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;
    }
  }

推荐阅读