advance_debounce.dart 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // 防抖函数上次触发的时间
  2. import 'dart:async';
  3. import 'package:flutter/material.dart';
  4. Map<String, DateTime> _funcDebounceLastCall = {};
  5. /// 函数防抖 (可自定义标识)
  6. /// 用于搜索框之类的频繁触发的方法,防止频繁触发,连续触发部分可能被忽略
  7. /// [func]: 要执行的方法
  8. /// [funcTag]: 方法标识符
  9. /// [milliseconds]: 要迟延的毫秒时间
  10. Function advanceDebounce(Function func, String funcTag,
  11. [int milliseconds = 2000]) {
  12. target() {
  13. String key = funcTag.toString();
  14. // 判断是否是第一次调用
  15. if (_funcDebounceLastCall[key] == null) {
  16. func.call();
  17. _funcDebounceLastCall[key] = DateTime.now();
  18. } else {
  19. // 判断是否超过了延迟时间
  20. if (DateTime.now()
  21. .difference(_funcDebounceLastCall[key]!)
  22. .inMilliseconds >
  23. milliseconds) {
  24. _funcDebounceLastCall[key] = DateTime.now();
  25. func.call();
  26. } else {
  27. print("[debounce] $funcTag skip");
  28. }
  29. }
  30. }
  31. target();
  32. return target;
  33. }
  34. class Debouncer {
  35. static Duration delay = const Duration(seconds: 1);
  36. static bool _isAvailable = true;
  37. static void run(VoidCallback action, {Duration? duration}) {
  38. if (_isAvailable) {
  39. _isAvailable = false;
  40. action();
  41. Timer(duration ?? delay, () {
  42. _isAvailable = true;
  43. });
  44. }
  45. }
  46. }