Dart/Flutter的防抖与节流

2023-11-23 0 1,156

Dart/Flutter的防抖与节流

防抖(debounce)

是指在触发事件后,在 n 秒内函数只能执行一次。如果在 n 秒内再次触发事件,将重新计算函数执行时间。防抖常用于实时搜索,当用户连续输入时,只有在停止输入后才会触发搜索接口。

// https://www.huizhanii.com
import 'dart:async';

Map<String, Timer> _funcDebounce = {};

/// 函数防抖
/// [func]: 要执行的方法
/// [milliseconds]: 要迟延的毫秒时间
Function debounce(Function func, [int milliseconds = 500]) {
  assert(func != null);
  Function target = () {
    String key = func.hashCode.toString();
    Timer _timer = _funcDebounce[key];
    if (_timer == null) {
      func?.call();
      _timer = Timer(Duration(milliseconds: milliseconds), () {
        Timer t = _funcDebounce.remove(key);
        t?.cancel();
        t = null;
      });
      _funcDebounce[key] = _timer;
    }
  };
  return target;
}

调用:

// https://www.huizhanii.com
void onSearch() {}

debounce(onSearch, 1000)();

节流(throttle)

是让函数有节制地执行,而不是无节制地触发一次就执行一次。节流的含义是在某个时间段内只能执行一次。节流常用于按钮重复提交的场景。

// https://www.huizhanii.com
import 'dart:async';

Map<String, bool> _funcThrottle = {};

/// 函数节流
/// [func]: 要执行的方法
Function throttle(Future Function() func) {
  if (func == null) {
    return func;
  }
  Function target = () {
    String key = func.hashCode.toString();
    bool _enable = _funcThrottle[key] ?? true;
    if (_enable) {
      _funcThrottle[key] = false;
      func().then((_) {
        _funcThrottle[key] = false;
      }).whenComplete(() {
        _funcThrottle.remove(key);
      });
    }
  };
  return target;
}

调用:

// https://www.huizhanii.com
Future<void> onSubmit() async {}

throttle(onSubmit)();

封装方法复用参考

// https://www.huizhanii.com
class CommonUtil {
  static const deFaultDurationTime = 300;
  static Timer timer;

  // 防抖函数
  static debounce(Function doSomething, {durationTime = deFaultDurationTime}) {
    timer?.cancel();
    timer = new Timer(Duration(milliseconds: durationTime), () {
      doSomething?.call();
      timer = null;
    });
  }

  // 节流函数
  static const String deFaultThrottleId = 'DeFaultThrottleId';
  static Map<String, int> startTimeMap = {deFaultThrottleId: 0};
  static throttle(Function doSomething, {String throttleId = deFaultThrottleId, durationTime = deFaultDurationTime, Function continueClick}) {
    int currentTime = DateTime.now().millisecondsSinceEpoch;
    if (currentTime - (startTimeMap[throttleId] ?? 0) > durationTime) {
      doSomething?.call();
      startTimeMap[throttleId] = DateTime.now().millisecondsSinceEpoch;
    } else {
      continueClick?.call();
    }
  }
  
}

使用

// https://www.huizhanii.com
GestureDetector(
      onTap: () => CommonUtil.throttle(onTap, durationTime: durationTime)
)

CommonUtil.debounce(searchApi)
收藏 (0)

微信扫一扫

支付宝扫一扫

点赞 (0)

免责声明

本资源仅限个人学习与研究使用,严禁用于任何商业用途!

1 网站名称:汇站网
2 永久网址:https://www.huizhanii.com
3 本站资源来源于网友投稿和付费购买,仅供编程人员及源代码爱好者下载参考与研究,不提供任何技术支持服务!
4 资源展示图片及相关信息仅供参考,不代表本站立场!本站仅作为信息存储平台
5 禁止在服务器和虚拟机上搭建运营,所有资源仅限本地调试与研究使用,不支持联网运行!
6 未经版权方授权,严禁用于商业用途。使用者如违反国家法律法规,需自行承担全部法律责任!
7 请在下载后24小时内删除!建议支持正版授权作品
8 如资源侵犯您的合法权益,请提供版权证明及相关作品信息发送至邮箱:972908224@qq.com,我们将及时处理
9 如遇下载链接失效或支付未到账,请联系站长处理
10 欢迎投稿优质源码或教程,审核通过后将获得相应奖励
11 资源收费仅用于维持网站正常运营
12 数字商品具有特殊性质,一经购买概不退款

汇站网 flutter Dart/Flutter的防抖与节流 https://www.huizhanii.com/33899.html

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

联系官方客服

为您解决烦忧 - 24小时在线 专业服务