Home > Software engineering >  How to refresh the screen after deleting a document?
How to refresh the screen after deleting a document?

Time:07-24

I am working on flutter app which will delete a document after clicking on delete button. To delete a document, I have defined the following function:

Future<void> deleteEvent(String eventId) async {
events
    .doc(eventId)
    .delete()
    .then((value) => print("Event Deleted"))
    .catchError((error) => print("Failed to delete Event: $error"));
}

I am calling this function whenever the delete button is pressed as follows:

 ElevatedButton(
     onPressed: () {
     deleteEvent(widget.eventId);
     },
     child: Padding(
     padding: EdgeInsets.all(4.0),
     child: Text('Delete'),
     ),

This is working fine. However, I want to refresh the screen as soon as the event is deleted. So that deleted event disappears from the screen after pressing the delete button. I have tried to use setState() method also:

Future<void> deleteEvent(String eventId) async {
setState(() {
  events
    .doc(eventId)
    .delete()
    .then((value) => print("Event Deleted"))
    .catchError((error) => print("Failed to delete Event: $error"));
  });
}

Still not able to achieve what I want to.

Update:

I am looking for a simpler alternative. Just a simple code or function that will refresh/reload the screen as soon as the delete function is called.

CodePudding user response:

You can stream builder to get documents so it will get updated asynchronously

Take a look at. How to add stream builder

CodePudding user response:

After your deleteEvent() function call in the onTap, you can call setState like this: setState(()=>{});

CodePudding user response:

SetState doesn't work because the delete function is async. setState is synchronous. Use s stream for the documents with a StreamBuilder instead that will automatically refresh or put a setState inside the .then() of your existing code and inside the setState repopulate the data in the widget after you await the data like this:

Future<void> deleteEvent(String eventId) async {
  events
    .doc(eventId)
    .delete()
    .then((value) => {
      //final List documents = await make call to firebase for documents
      //setState({
      //update the UI with the above documents
    })
    .catchError((error) => print("Failed to delete Event: $error"));
}
  • Related