如何在Dismissible的onDismissed()动作被触发之前添加动作?

时间:2019-01-21 01:17:43

标签: flutter

我想在AlertBox动作发生之前添加一个小的onDismissed()吗?

因此,用户从列表中滑动该项目将其删除,但是就在操作发生之前,我想问他是否确定。

当前的Dismissible小部件可以吗?

编辑:

onDismissed: (direction) {
    final User _deletedItem = this._items[index];

    showDialog(
      context: context,
      barrierDismissible: false, // user must tap a button
      builder: (BuildContext context) {
        return AlertDialog(
          content: Text(
              'Are you sure you want to delete this?'),
          actions: <Widget>[
            FlatButton(
              child: Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop(false);
              },
            ),
            FlatButton(
              child: Text('OK'),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    ).then((answer) {
      if (answer == true) {
        setState(() {
          this._items.removeAt(index);
        });

        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text("Deleted"),
            duration: Duration(milliseconds: 2000),
          ),
        );
      } else {
        setState(() {
          this._items.insert(index, _deletedItem);
        });
      }
    });
  },

2 个答案:

答案 0 :(得分:1)

很抱歉,到目前为止,尚无办法使用标准的“可禁用”来阻止物品滑动。

如果您想实现自己想要的目标,则可能希望实现自己的自定义方式,方法是使用GestureDetector拥有孩子ListTile,然后监听horizontalDrag()事件。

我建议的更简单的方法是让用户滑动(并使项目消失),然后立即显示SnackBar告诉用户是否要撤消该删除操作,您可以处理撤消操作,方法是将该项目重新放回到列表中。


编辑: 要执行删除和撤消操作,

GlobalKey<ScaffoldState> _key = GlobalKey(); // added
List<String> _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
                  ),
                ),
              );
            });
          },
        );
      },
    ),
  );
}

屏幕截图

enter image description here

答案 1 :(得分:0)

您可能需要confirmDismiss属性吗?