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));
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容