Flutter_01_封装高频事件防抖

import 'dart:async';

/// 支持0-1个参数,实现防抖
/// func  需要执行的逻辑
/// delay 设置延迟时长
useDebounce(Function? func,
    {Duration delay = const Duration(milliseconds: 500)}) {
  Timer? _debounce;
  // 2、可选位置参数
  Function target = ([arg]) {
    // 1、为空则不会执行取消定时器的操作
    _debounce?.cancel();
    _debounce = Timer(delay, () {
      // 3、判断是否传入参数
      arg != null ? func?.call(arg) : func?.call();
    });
  };
  return target;
}
posted @ 2021-08-05 22:40  拖延症的理想主义者  阅读(282)  评论(0编辑  收藏  举报