如何实现滑动删除列表视图以从Firestore中删除数据

时间:2019-04-30 09:56:24

标签: android firebase dart flutter google-cloud-firestore

我对扑镖和飞镖很陌生,所以这可能是一个基本问题。但是,我想知道的是如何在列表视图中实现滑动删除方法以从Firestore中删除数据。

我尝试使用Dissmissible函数,但我不了解如何显示列表,而且我似乎也无法理解如何删除所选数据。

这是我的飞镖代码

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

}

3 个答案:

答案 0 :(得分:2)

您应该使用Dismissible小部件。我将其用于从Firestore检索的收件箱列表。在您的EachList内返回类似这样的内容

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: ...,
      );

    });

重要提示:要删除列表项,您还需要从快照列表中删除该项,而不仅是从firestore中删除:

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

此处是文档:Implement Swipe to Dismiss

下面是Flutter团队的视频:Widget of the week - Dismissilbe

答案 1 :(得分:0)

您可以使用flutter_slidable软件包来实现相同的目的。

您还可以使用相同的软件包在Github上查看我的Cricket Team,其中我做了您想实现的目标。

有关如何使用软件包的示例已写成here

答案 2 :(得分:0)

我想补充一点,当从Firestore删除文档时,不需要await,因为该插件会自动缓存所做的更改,然后在再次建立连接时将其同步。

例如,我曾经使用这种方法

  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());
  }

我正在等待呼叫通过,但是这阻止了其他任何呼叫通过,只允许一个。但是,删除此await标签可以解决我的问题。

现在,我可以脱机删除文档,并且在重新建立连接后,更改将与Firestore同步。在控制台中观看非常酷。

我建议您观看this video about offline use with Firestore