当前位置: 首页 > news >正文

Flutter自定义通用防抖的实现

在前端项目开发中,点击事件的防抖是一个永远无法错开的点,特别是针对一些复杂的业务场景,如果不做好防抖操作,就会导致页面或功能触发多次,引发异常或闪退。

在Flutter中可以通过扩展函数的特性 对Function增加全局扩展函数,实现防抖效果。

具体如下:

extension FunctionExt on Function {VoidCallback throttle() {return FunctionProxy(this).throttle;}// 立即执行目标操作,同时给出一个延迟的时间,// 在该时间范围内如果再次触发了事件,该次事件会被忽略,直到超过该时间范围后触发事件才会被处理。VoidCallback throttleWithTimeout({int? timeout}) {return FunctionProxy(this, timeout: timeout).throttleWithTimeout;}// 在触发事件时,不立即执行目标操作,而是给出一个延迟的时间,// 在该时间范围内如果再次触发了事件,则重置延迟时间,直到延迟时间结束才会执行目标操作。VoidCallback debounce({int? timeout}) {return FunctionProxy(this, timeout: timeout).debounce;}
}class FunctionProxy {static final Map<String, bool> _funcThrottle = {};static final Map<String, Timer> _funcDebounce = {};final Function? target;final int timeout;FunctionProxy(this.target, {int? timeout}) : timeout = timeout ?? 500;// 节流(默认延迟)void throttle() async {String key = hashCode.toString();bool enable = _funcThrottle[key] ?? true;if (enable) {_funcThrottle[key] = false;try {await target?.call();} catch (e) {rethrow;} finally {_funcThrottle.remove(key);}}}// 节流(自定义延迟)void throttleWithTimeout() {String key = hashCode.toString();bool enable = _funcThrottle[key] ?? true;if (enable) {_funcThrottle[key] = false;Timer(Duration(milliseconds: timeout), () {_funcThrottle.remove(key);});target?.call();}}//延迟顺序执行的防抖void debounce() {String key = hashCode.toString();Timer? timer = _funcDebounce[key];timer?.cancel();timer = Timer(Duration(milliseconds: timeout), () {Timer? t = _funcDebounce.remove(key);t?.cancel();target?.call();});_funcDebounce[key] = timer;}
}

在使用的地方

              onBackPressed: () {}.throttleWithTimeout(timeout: 500)

这种方案只是提供了一种防抖的实现,当然也可以自定义通用的Button,通过点击事件触发的时间自行判断处理。

http://www.lryc.cn/news/411298.html

相关文章:

  • C# Unity 面向对象补全计划 之 继承(字段与属性)
  • leetcode202. 快乐数,双指针法巧用
  • 基于Cobbler实现多版本系统批量部署
  • 一投就中不是梦,录取率>80%,最快1个月就见刊,计算机沾边就收,认可度还不低
  • 【课程系列06】某乎AI大模型全栈工程师-第6期
  • Prompt——3分钟掌握,润色论文的7条经典指令。帮助很大,一定要看!
  • ARM学习(31)编译器对overlay方式的支持
  • 【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
  • 软件测试——用例篇(上)
  • Flink中三种模式:YARN Session 模式、YARN Per-Job 模式和 YARN Application 模式提交任务命令
  • DBMS-1.2 关系运算
  • Python——继承
  • 程序员转型AI大模型好转吗?成功率高吗?
  • 关于 Postman 这些你都知道吗?
  • ReentrantLock
  • python | TypeError: list indices must be integers or slices, not tuple
  • 链码简介及MATLAB提取彩色图像链码
  • 二叉树,二叉查找树,平衡二叉树
  • 《零散知识点 · SpringBoot 整合邮件功能》
  • 编程小白如何成为大神?大学新生的最佳入门攻略
  • 使用 PyInstaller 和 Hook 文件打包 APK 解析工具
  • 【分布式】分库分表知识点大全
  • FreeRTOS中的定时器:xTimerCreate ,xTimerStart ,xTimerStop
  • 【网络安全】文件上传黑白名单及数组绕过技巧
  • 4.2、存储管理-页式存储
  • 60个常见的 Linux 指令
  • DockerRedis基础
  • oracle读写时相关字符集详解
  • OverlayFS 文件系统介绍
  • 【C++】用Lua绑定C/C++对象,实现对脚本调用(依赖LuaBridge实现)