如何使用flutter从Cloud Firestore中删除特定文档?

时间:2020-08-27 14:21:57

标签: firebase flutter google-cloud-firestore

我需要有关使用flutter操纵数据的帮助,该flutter存储在Cloud Firestore中。我创建了一个函数,可以在按下图标时添加数据,而在您点击2次时删除数据。

这是我的代码:

void switcherIsFavSalon() async {
  var firebaseUser = await FirebaseAuth.instance.currentUser();
  var docRef = Firestore.instance
      .collection('customers')
      .document(firebaseUser.uid)
      .collection('favSalons');

  if (isFavSalon == false) {
    setState(() {
      favIcon = 'assets/icons/heart_filled.png';
      isFavSalon = true;
      docRef.add({
        "salonName": widget.salonName,
        "workTime": widget.workTime,
        "location": widget.location,
        "rating": widget.rating
  // here is add method
      });
    });
  } else {
    setState(() {
      favIcon = 'assets/icons/heart_border.png';
      isFavSalon = false;
      docRef. //i need delete method here
    });
  }
}

有人可以帮我,因为我对此很陌生。

1 个答案:

答案 0 :(得分:0)

        void switcherIsFavSalon() async {
          var firebaseUser = await FirebaseAuth.instance.currentUser();
          var docRef = Firestore.instance
              .collection('customers')
              .document(firebaseUser.uid)
              .collection('favSalons');
        
          if (isFavSalon == false) {
            setState(() {
              favIcon = 'assets/icons/heart_filled.png';
              isFavSalon = true;
             await docRef.add({
                "salonName": widget.salonName,
                "workTime": widget.workTime,
                "location": widget.location,
                "rating": widget.rating
          // here is add method
              });
            });
          } else {
            setState(() {
              favIcon = 'assets/icons/heart_border.png';
              isFavSalon = false;
              });
docRef=await Firestore.instance.collection('customers').document(firebaseUser.uid)
              .collection('favSalons');
       await docRef.getDocuments().then((value) {  
                                             value.documents.forEach((element) {
if(element['salonName']==widget.salonName)
    await docRef.document(element.documentID).delete();
      });
     });
}