在flutter中从cloud_firestore删除文档

时间:2020-09-15 07:33:37

标签: firebase flutter dart google-cloud-firestore

我要返回一个streamBuilder,并且在streamBuider内部,它会返回一个小部件。
现在,我包装了一个可关闭的小部件,以便可以从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!");
                });
              },           

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

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

3 个答案:

答案 0 :(得分:1)

Scaffold( resizeToAvoidBottomInset: true, // widgets still get squeezed body: SingleChildScrollView( child: Container( color: Colors.black54, key: widget.key, padding: EdgeInsets.only(left:50, right:50, top:30, bottom: 100), child: Container( decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(5), border: Border.all(color: Colors.redAccent, width: 2), ), padding: EdgeInsets.symmetric(horizontal: 50, vertical: 30), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(horizontal: 50), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ ], ), // SizedBox(height: 10), ], ), ), ), ), ), 将生成一个新的随机ID,因此,如果您无权访问该ID,则需要执行以下操作:

doc()

使用 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(), 下的所有文档,因此可以向文档中添加唯一字段,然后在for循环中可以获取ID:

eventDetails

然后您可以将其删除:

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

这样,您无需两次提取文档。

答案 1 :(得分:0)

我只需要使用,
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,
          ),
        );
      },
    );
  }

答案 2 :(得分:0)

您可以随时查询文档以获取文档 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();
}