【问题标题】:Deleting document from cloud_firestore in flutter在flutter中从cloud_firestore中删除文档
【发布时间】:2021-01-01 22:22:51
【问题描述】:

我返回一个streamBuilder,在streamBuider 内部,它返回一个小部件。
现在我已经用dismissible 包装了一个小部件,以便我可以从cloud_firestore 的集合中删除文档。

showingTheSelectedDateEvents() {
    List<Widget> listViewContainer = [];

    return StreamBuilder<QuerySnapshot>(
      stream: firestoreInstance.collection('eventDetails').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: Colors.lightBlueAccent,
            ),
          );
        }
        String theDatabaseDate;
        final allDocuments = snapshot.data.docs;
        //here we get all the documents from the snapshot.
        for (var i in allDocuments) {
          theDatabaseDate = i.data()['dateTime'];
          if (theDatabaseDate == theDataProvider.databaseSelectedDate) {
            print(theDatabaseDate +
                " is same as " +
                theDataProvider.databaseSelectedDate);
            listViewContainer.add(Dismissible(
              key: ObjectKey(snapshot.data.docs.elementAt(0)),
              onDismissed: (direction) {
                firestoreInstance
                    .collection("eventDetails")
                    .doc()
                    .delete()
                    .then((_) {
                  print("success!");
                });
              },
             child://here
          
            ));
            print(listViewContainer.length);
          } else {
            print("no any events for today");
          }
        }
        return Expanded(
          child: ListView(
            reverse: true,
            padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
            children: listViewContainer,
          ),
        );
      },
    );
  }

我尝试使用此方法从 cloud_firestore 中删除数据

key: ObjectKey(snapshot.data.docs.elementAt(0)),
onDismissed: (direction) {
                firestoreInstance
                    .collection("eventDetails")
                    .doc()
                    .delete()
                    .then((_) {
                  print("success!");
                });
              },           

我想从集合中删除特定文档
我不知道该怎么做。
这是数据库模型

我正在尝试删除eventDetails集合的文档。

【问题讨论】:

  • 您要删除什么文件?你能告诉我们你的数据库模型吗?
  • @Uni 看看更新后的问题
  • firestoreInstance .collection("eventDetails") .doc("你需要在这里传递你的eventdetails集合中的documentID") .delete()
  • @Reign 你能帮我获取当前文档的文档ID吗?
  • snapshot.key 将获取文档 ID

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

您可以随时查询文档以获取文档ID并执行删除。

var collection = FirebaseFirestore.instance.collection('users');
var snapshot = await collection.where('age', isGreaterThan: 20).get();
for (var doc in snapshot.docs) {
 await doc.reference.delete();
}

要删除所有文档,请遍历QueryDocumentSnapshot

var collection = FirebaseFirestore.instance.collection('collection');
var querySnapshots = await collection.get();
for (var doc in querySnapshots.docs) {
  await doc.reference.delete();
}

【讨论】:

    【解决方案2】:

    我只需要使用,
    i.id
    获取文档 ID。我可以通过滑动从 Firestore 中删除文档。

    这是完整的代码,

     showingTheSelectedDateEvents() {
        List<Widget> listViewContainer = [];
    
        return StreamBuilder<QuerySnapshot>(
          stream: firestoreInstance.collection('eventDetails').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(
                  backgroundColor: Colors.lightBlueAccent,
                ),
              );
            }
            String theDatabaseDate;
            final allDocuments = snapshot.data.docs;
            //here we get all the documents from the snapshot.
            for (var i in allDocuments) {
              // if(i.data()["subject"] == "Mathemtics")
    
              theDatabaseDate = i.data()['dateTime'];
              if (theDatabaseDate == theDataProvider.databaseSelectedDate) {
                print(theDatabaseDate +
                    " is same as " +
                    theDataProvider.databaseSelectedDate);
                listViewContainer.add(Dismissible(
                  key: ObjectKey(snapshot.data.docs.elementAt(0)),
                  onDismissed: (direction) async {
                    firestoreInstance.collection("eventDetails").doc(i.id).delete();
    
                    // allDocuments.removeAt(0);
                  },
                  background: Container(
                    alignment: Alignment.centerRight,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(0, 0, 20, 0),
                      child: Text(
                        "Slide To Remove",
                        style: TextStyle(
                            fontSize: 15,
                            fontFamily: "Poppins",
                            color: Colors.black),
                      ),
                    ),
                    decoration: BoxDecoration(color: Color(0xFFF4F5F6)),
                  ),
                  child: Widgets(
                    containerHeight: 170,
                    thePaddingValue:
                        EdgeInsets.only(left: 90, right: 10, top: 20, bottom: 20),
                    iconSize: 60,
                    chapterName: i.data()['chapterName'],
                    chapterNumber: i.data()['chapterNumber'],
                    meetType: i.data()['meetType'],
                    meetIcon: Icons.video_call,
                    subject: i.data()['subject'],
                    lectureTime: "09:30",
                    teacherImage:
                        AssetImage("assets/images/IMG-20200817-WA0000.jpg"),
                    teacherName: "Alex Jesus",
                  ),
                ));
                print(listViewContainer.length);
              } else {
                print("no any events for today");
              }
            }
            return Expanded(
              child: ListView(
                reverse: true,
                padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
                children: listViewContainer,
              ),
            );
          },
        );
      }
    

    【讨论】:

      【解决方案3】:

      doc() 会生成一个新的随机 id,因此如果您无法访问该 id,那么您需要执行以下操作:

          FirebaseFirestore.instance
              .collection("eventDetails")
              .where("chapterNumber", isEqualTo : "121 ")
              .get().then((value){
                value.docs.forEach((element) {
                 FirebaseFirestore.instance.collection("eventDetails").doc(element.id).delete().then((value){
                   print("Success!");
                 });
                });
              });
      

      使用where() 条件获取所需文档并将其删除。


      因为在您的代码中您正在使用:

      return StreamBuilder<QuerySnapshot>(
            stream: firestoreInstance.collection('eventDetails').snapshots(),
      

      这里您正在获取eventDetails 下的所有文档,因此您可以在文档中添加一个唯一字段,然后在 for 循环中您可以获得 id:

      for (var i in allDocuments) {
                if(i.data()["subject"] == "Mathemtics")
                     docId = i.id;
      

      然后你可以删除它:

                    onDismissed: (direction) {
                      FirebaseFirestore.instance
                          .collection("eventDetails")
                          .doc(docId)
                          .delete()
                          .then((_) {
                        print("success!");
                      });
                    },
      

      这样你就不需要两次获取文档了。

      【讨论】:

        猜你喜欢
        • 2019-04-30
        • 1970-01-01
        • 2020-10-31
        • 2021-06-26
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        • 2020-09-01
        相关资源
        最近更新 更多