How to implement a swipe to delete listview to remove data from firestore

5,217

Solution 1

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

return Dismissible(
        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 list
  setState(() {
    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.

Share:
5,217
Damsara Perera
Author by

Damsara Perera

Updated on December 11, 2022

Comments

  • Damsara Perera
    Damsara Perera over 1 year

    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 firestore too.

    I tried using the Dissmissible function but i dont understand how to display the list and I cant seem to understand how to remove the selected data as well.

    This here is my dart code

    Widget build(BuildContext context) {
    return new Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: new AppBar(
        centerTitle: true,
        automaticallyImplyLeading: false,
        title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: 
    <Widget>[
          Text("INVENTORY",textAlign: TextAlign.center,) ,new IconButton(
              icon: Icon(
                Icons.home,
                color: Colors.black,
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  SlideLeftRoute(widget: MyHomePage()),
                );
              })]),
      ),body: ListPage(),
    );
      }
    }
    
     class ListPage extends StatefulWidget {
       @override
      _ListPageState createState() => _ListPageState();
      }
    
    class _ListPageState extends State<ListPage> {
    
    Future getPosts() async{
    var firestore = Firestore.instance;
    
    QuerySnapshot gn = await 
    firestore.collection("Inventory").orderBy("Name",descending: 
    false).getDocuments();
    
    return gn.documents;
    
    }
    
    @override
    Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: getPosts(),
          builder: (_, snapshot){
        if(snapshot.connectionState == ConnectionState.waiting){
          return Center(
            child: Text("Loading"),
          );
        }else{
    
          return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder:(_, index){
                return EachList(snapshot.data[index].data["Name"].toString(), 
    snapshot.data[index].data["Quantity"]);
              });
        }
      }),
     );
     }
    }
    
    
    class EachList extends StatelessWidget{
    final String details;
    final String name;
    EachList(this.name, this.details);
    @override
     Widget build(BuildContext context) {
    // TODO: implement build
    return new Card(
      child:new Container(
        padding: EdgeInsets.all(8.0),
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            new Row(
              children: <Widget>[
                new CircleAvatar(child: new Text(name[0].toUpperCase()),),
                new Padding(padding: EdgeInsets.all(10.0)),
                new Text(name, style: TextStyle(fontSize: 20.0),),
              ],
            ),
            new Text(details, style: TextStyle(fontSize: 20.0))
          ],
        ),
      ),
    );
      }
    
    }
    
  • Damsara Perera
    Damsara Perera about 5 years
    it works! Thanks a lot. I was wondering though how to do it if I wanted to edit the details as well?
  • Damsara Perera
    Damsara Perera about 5 years
    and also. What does the deleteMessage function do?
  • tyirvine
    tyirvine almost 4 years
    As @Marco mentions, it is wise to remove the document from the snapshot as well. I just use a BLoC to handle this