Flutter ListView delete and undo operation

前端 未结 2 1777
挽巷
挽巷 2021-01-13 21:36

How can I implement a ListView that has a Dismissible widget, and when I swipe, I can delete the item, but how can I bring it back when tapping say

2条回答
  •  醉梦人生
    2021-01-13 22:17

    All you needed is

    _list.insert(index, yourDeletedItem);
    

    Here is the complete code with SnackBar added.

    GlobalKey _key = GlobalKey(); // added
    List _list = List.generate(10, (index) => "${index}");
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        key: _key, // added
        appBar: AppBar(title: Text("App")),
        body: ListView.builder(
          itemCount: _list.length,
          itemBuilder: (context, index) {
            return Dismissible(
              key: Key(_list[index]),
              child: ListTile(title: Text(_list[index])),
              background: Container(color: Colors.red),
              onDismissed: (direction) {
                setState(() {
                  // added this block 
                  String deletedItem = _list.removeAt(index);
                  _key.currentState
                   ..removeCurrentSnackBar()
                   ..showSnackBar(
                    SnackBar(
                      content: Text("Deleted \"${deletedItem}\""),
                      action: SnackBarAction(
                        label: "UNDO",
                        onPressed: () => setState(() => _list.insert(index, deletedItem),) // this is what you needed
                      ),
                    ),
                  );
                });
              },
            );
          },
        ),
      );
    }
    

    Screenshot

提交回复
热议问题