flutter:防重复点击 【节流】【防抖】

2,783 阅读1分钟

概念

节流是忽略操作,在触发事件时,立即执行目标操作,如果在指定的时间区间内再次触发了事件,则会丢弃该事件不执行,只有超过了指定的时间之后,才会再次触发事件。

防抖是延时操作,在触发事件时,不立即执行目标操作,而是给出一个延迟的时间,如果在指定的时间区间内再次触发了事件,则重置延时时间,只有当延时时间走完了才会真正执行。

使用 Extension + Timer + 闭包函数

1. 扩展Function,添加节流功能

extension ThrottleExtension on Function {
  void Function() throttle([int milliseconds = 500]) {
    bool _isAllowed = true;
    Timer? _throttleTimer;
    return () {
      if (!_isAllowed) return;
      _isAllowed = false;
      this();
      _throttleTimer?.cancel();
      _throttleTimer = Timer(Duration(milliseconds: milliseconds), () {
        _isAllowed = true;
      });
    };
  }
}

2. 扩展Function,添加防抖功能

extension DebounceExtension on Function {
  void Function() debounce([int milliseconds = 500]) {
    Timer? _debounceTimer;
    return () {
      if (_debounceTimer?.isActive ?? false) _debounceTimer?.cancel();
      _debounceTimer = Timer(Duration(milliseconds: milliseconds), this);
    };
  }
}

使用闭包函数,维护内部局部变量 timer

使用方式

//点击事件
onPressed: () {
          setState(() {
            _counter++;
          });
        }.throttle()