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

冷暖自知 提交于 2020-12-12 06:04:33

问题


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))
      ],
    ),
  ),
);
  }

}

回答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




回答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.




回答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



来源:https://stackoverflow.com/questions/55918425/how-to-implement-a-swipe-to-delete-listview-to-remove-data-from-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!