Flutter Dismissible坚持必须从树中删除列表项

iBo*_*101 5 dart flutter

我正在使用“可放行的物品”列表,并希望在一个方向上滑动即可删除该物品,而在另一个方向上滑动即可启动该物品的编辑。但是,Flutter坚持必须在onDismissed回调中从树中删除Dismissible项。我试过重新插入该项目,但这不起作用。有任何想法吗?下面是创建列表项的代码摘录:

  return new Dismissible(
    key: new ObjectKey(item),
    direction: DismissDirection.horizontal,
    onDismissed: (DismissDirection direction) {
      setState(() {
        item.deleteTsk();
      });
      if (direction == DismissDirection.endToStart){
        //user swiped left to delete item
        _scaffoldKey.currentState.showSnackBar(new SnackBar(
          content: new Text('You deleted: ${item.title}'),
          action: new SnackBarAction(
            label: 'UNDO',
            onPressed: () { handleUndo(item); }
          )
        ));
      }
      if (direction == DismissDirection.startToEnd){
        //user swiped right to edit so undo the delete required by flutter
        Async.scheduleMicrotask((){handleUndo(item);});
        Navigator.of(context).pushNamed('/tskedit');
      }
    },
  ...
Run Code Online (Sandbox Code Playgroud)

小智 17

为此,您可以使用小部件的confirmDismiss功能Dismissible

如果您不希望小部件被关闭,那么您只需false要从confirmDismiss.

不要onDismissed用来做你的后滑动处理,confirmDismiss而是使用,它会为你提供滑动方向,就像onDismissed.

以下是confirmDismiss函数的官方文档:

为应用程序提供确认或否决待处理解雇的机会。如果返回的 Future 完成为真,则此小部件将被解除,否则将移回其原始位置。如果返回的 Future 完成为 false 或 null,则 [onResize]

这是一个例子:

Dismissible(
  confirmDismiss: (direction) async {
    if (direction == DismissDirection.startToEnd) {
      /// edit item
      return false;
    } else if (direction == DismissDirection.endToStart) {
      /// delete
      return true;
    }
  },
  key: Key(item.key),
  child: Text(item.name),
)
Run Code Online (Sandbox Code Playgroud)


Col*_*son 5

Dismissible只要项目密钥发生更改,遗嘱就会认为您的项目已被撤消。假设您的商品类别为MyItem。如果您MyItem.fromMyItem类中实现了一个构造函数,该构造函数将字段复制过来,例如:

class MyItem {
  MyItem({ @required this.title, @required this.color });
  MyItem.from(MyItem other) : title = other.title, color = other.color;
  final String title;
  final Color color;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以替换为handleUndo(item)handleUndo(new MyItem.from(item))从而使您的名称new ObjectKey(item)与以前ObjectKey使用的旧版本不同(假设您未operator ==在上实现MyItem)。