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

如何实现Flutter Dismissible仅单次滑动触发,禁用多手势滑动

解决Dismissible组件禁止多滑动操作的问题

要实现仅允许单次滑动触发,可通过状态控制拦截多滑动操作,具体步骤如下:

  • 添加状态变量跟踪滑动状态
    在页面的State类中定义布尔变量_isDismissing,标记当前是否有正在执行的滑动删除操作。

  • 拦截滑动触发逻辑
    利用Dismissible的confirmDismiss属性,在滑动开始前判断是否允许执行操作:若已有滑动正在进行则拒绝本次请求,否则允许并标记状态为正在滑动。

  • 操作完成后重置状态
    在删除接口调用完成(含异步场景)后,将状态变量重置,恢复后续滑动的可触发状态。

修改后的完整代码示例:

class YourAccountPage extends StatefulWidget {
  const YourAccountPage({super.key});

  @override
  State<YourAccountPage> createState() => _YourAccountPageState();
}

class _YourAccountPageState extends State<YourAccountPage> {
  bool _isDismissing = false;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: // 此处替换为你的数据请求Future
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Center(child: CircularProgressIndicator());
        }
        
        return ListView.builder(
          itemCount: snapshot.data!.length,
          itemBuilder: (context, index) {
            return Dismissible(
              background: Container(
                color: Colors.red,
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      "Delete",
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
              direction: DismissDirection.endToStart,
              key: Key(snapshot.data![index].id.toString()),
              confirmDismiss: (direction) async {
                if (_isDismissing) return false;
                setState(() => _isDismissing = true);
                return true;
              },
              onDismissed: (direction) async {
                // 执行删除操作
                await accountSettings.deleteAccount(
                  snapshot.data![index].id.toString()
                );
                // 操作完成后重置状态
                setState(() => _isDismissing = false);
              },
            );
          },
        );
      },
    );
  }
}

注意:若删除操作是异步请求,必须等待请求完成后再重置状态,避免提前恢复可滑动状态导致多滑动触发。

内容的提问来源于stack exchange,提问作者Ethylion

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:32:44