Home > Back-end >  delete data stored in firestore
delete data stored in firestore

Time:10-13

I have a button that stores the data selected by the user in the database in firstore firebase but I would like that same button to also be able to delete the data that has just been saved in the database. To do this, create an onpressed that will help me delete or undo the data that was just stored but I can't find a way to do it.

That is the method I use to store the data in my database

ElevatedButton(
          onPressed: () async {
            await users.add({ //I use the add method to add but there is no delete method.
              'Fatiga': fatiga,
              'Miccion': miccion,
              'Flujo Vaginal': flujoVaginal,
              'Estreñimiento': estrenimiento,
              'Acidez Gastrica': acidezGastrica,
              'Sangrado Nasal': sangradoNasal,
              'Sangrado de encias': sangradoEncias,
              'Hinchazon': hinchazon,
              'Problemas respiratarios': problemasRespiratorios,
              'Fecha ingreso sintoma': dateTime.toString(),
            }).then((value) => (value) => print('User added'));
            final snackBar = SnackBar(
              content: const Text('Sintomas guardados'),
              action: SnackBarAction(
                label: 'UNDO',
                onPressed: () async {
                  //This is where I would like the data that was just stored to be deleted
                },
              ),
            );
            ScaffoldMessenger.of(context).showSnackBar(snackBar);
          },
          child: Text("Guardar"))

CodePudding user response:

Delete a single document:

var collection = FirebaseFirestore.instance.collection('users');
await collection.doc('document_id').delete();

Deleting documents related to some condition:

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

Deleting all the documents:

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