Skip to content Skip to sidebar Skip to footer

How To Implement A Swipe To Delete Listview To Remove Data From Firestore

Im very new to flutter and dart so this might be a basic question. However, what I would like to know is how to implement a swipe to delete method in a listview to delete data from

Solution 1:

You should use Dismissible widget. I used it for an inbox list retrieved from Firestore. Inside your EachList return something like this

returnDismissible(
        direction: DismissDirection.startToEnd,
        resizeDuration: Duration(milliseconds: 200),
        key: ObjectKey(snapshot.documents.elementAt(index)),
        onDismissed: (direction) {
          // TODO: implement your delete function and check direction if needed_deleteMessage(index);
        },
        background: Container(
          padding: EdgeInsets.only(left: 28.0),
          alignment: AlignmentDirectional.centerStart,
          color: Colors.red,
          child: Icon(Icons.delete_forever, color: Colors.white,),
        ),
        // secondaryBackground: ..., child: ...,
      );

    });

IMPORTANT: in order to remove the list item you'll need to remove the item from the snapshot list as well, not only from firestore:

_deleteMessage(index){
  // TODO: here remove from Firestore, then update your local snapshot listsetState(() {
    snapshot.documents.removeAt(index);
  });
}

Here the doc: Implement Swipe to Dismiss

And here a video by Flutter team: Widget of the week - Dismissilbe

Solution 2:

You can use the flutter_slidable package to achieve the same.

You can also check out my Cricket Team on Github in which I have did the same you want to achieve, using same package.

Example for how to use package are written here.

Solution 3:

I'd like to add that when deleting a document from Firestore, no await is needed as the plugin automatically caches the changes and then syncs them up when there is a connection again.

For instance, I used to use this method

  Future deleteWatchlistDocument(NotifierModel notifier) async {
    final String uid = await _grabUID();
    final String notifierID = notifier.documentID;
    return await _returnState(users.document(uid).collection(watchlist).document(notifierID).delete());
  }

in which I was waiting for the call to go through, however this prevented any other call to go through and only allowed one. Removing this await tag however solved my issue.

Now I can delete documents offline, and the changes will sync up with Firestore when a connection is regained. It's pretty cool to watch in the console.

I'd recommend watching this video about offline use with Firestore

Post a Comment for "How To Implement A Swipe To Delete Listview To Remove Data From Firestore"