You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Slidable自动关闭时执行onPress中的逻辑?

解决方案

先把重复的逻辑抽成独立方法,方便复用:

void _resetItemStatus(Item item) {
  item.selectedCount = 0;
  item.isSelected = false;
  widget.providerValue.selectedCheckItem?.remove(item);
  widget.providerValue.notifyListeners();
}

然后给Slidable加上onClose回调(该回调会在组件自动关闭时触发),同时让SlidableAction的onPressed也指向这个方法:

Slidable(
  closeOnScroll: true,
  key: UniqueKey(),
  // 自动关闭时触发逻辑
  onClose: (context) => _resetItemStatus(item),
  endActionPane: ActionPane(
    extentRatio: 0.1,
    openThreshold: 0.2,
    closeThreshold: 0.1,
    motion: const BehindMotion(),
    children: [
      SlidableAction(
        key: UniqueKey(),
        onPressed: (context) => _resetItemStatus(item),
        backgroundColor: context.suit200Red,
        icon: Icons.delete,
        label: 'İptal',
      ),
    ],
  ),
  child: MaxListTile(),
)

如果你的slidable版本没有Slidable.onClose,可以改用ActionPane.onClose属性:

endActionPane: ActionPane(
  // ...其他属性
  onClose: () => _resetItemStatus(item),
  children: [
    // ...SlidableAction
  ],
)

这样不管是点击按钮触发,还是滑动导致组件自动关闭,都会执行你需要的逻辑。


内容的提问来源于stack exchange,提问作者NURİ ÜLGEN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:14:55