flutter 避免按钮连续点击,重复响应封装

在一些计算较为复杂、操作较为耗时或者发送请求的操作中,如果事件持续触发,除了带来性能上的负担,还会导致糟糕的用户体验

为了按钮重复点击后触发事件,在调用事件方法后,给一个延时时间,在该时间范围内如果再次点击按钮,不触发事件,延时结束后,点击才可再次响应

按钮封装

class MyButtons {

  static int clickSpaceTime = 2000;//延时2s

  static Widget textButton({
    Widget child,
    VoidCallback onPressed,
    Color backgroundColor,
    double radius,
    //边界颜色
    Color sideColor,
  }) {
    bool bCanPress = true;
    return TextButton(
        onPressed: ()  {
          ///避免重复响应
          if(onPressed != null && bCanPress) {
            bCanPress = false;
            onPressed();
            Future.delayed(Duration(milliseconds: clickSpaceTime), (){
              bCanPress = true;
            });
          }
          if(!bCanPress) {
            print("$child按钮被重复点击");
          }
        },
        child: child,
        style: ButtonStyle(
            padding: MaterialStateProperty.all(EdgeInsets.zero),
            shape: MaterialStateProperty.all(RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(radius ?? 0))),
            overlayColor: MaterialStateProperty.all(
                (backgroundColor == null || backgroundColor == Colors.white)
                    ? Colors.Black.withOpacity(0.1)
                    : Colors.white.withOpacity(0.2)),
            backgroundColor: MaterialStateProperty.all(
                backgroundColor ?? Colors.transparent),
            side: sideColor != null
                ? MaterialStateProperty.all(
                    BorderSide(color: sideColor, width: 1))
                : null));
  }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值