Throttler<T> class

节流工具类

在指定时间内最多执行一次,适用于:

  • 滚动加载:滚动过程中限制加载频率
  • 按钮防重复点击:防止用户快速多次点击
  • 实时搜索:限制请求频率避免服务器压力
  • 窗口大小调整:限制重新计算布局的频率

工作原理

调用时间线:  |--A--B--C--|--D--|--E--|
             0  100 200   500   700   900 (毫秒)

throttleInterval = 400ms, leading = true, trailing = true:
- A 调用(0ms):立即执行(leading),开始节流窗口
- B 调用(100ms):在节流窗口内,保存为待执行
- C 调用(200ms):在节流窗口内,替换 B 为待执行
- 400ms:节流窗口结束,执行 C(trailing)
- D 调用(500ms):立即执行(新的 leading)
- E 调用(700ms):在节流窗口内,保存为待执行
- 900ms:节流窗口结束,执行 E(trailing)

结果:执行了 A, C, D, E(跳过了 B)

与防抖的区别

特性 防抖 (Debounce) 节流 (Throttle)
执行时机 等待静默期后执行 固定间隔执行
持续调用 永远不执行(直到停止) 定期执行
适用场景 搜索输入 滚动加载

基础用法

final throttler = Throttler<void>(
  duration: Duration(seconds: 1),
);

// 滚动监听
scrollController.addListener(() {
  throttler.call(() async {
    await loadMoreData();
  });
});

Leading 模式

// 首次调用立即执行,后续被节流
final throttler = Throttler<void>(
  duration: Duration(seconds: 1),
  leading: true,
  trailing: false,
);

Trailing 模式

// 节流窗口结束后执行最后一次调用
final throttler = Throttler<void>(
  duration: Duration(seconds: 1),
  leading: false,
  trailing: true,
);

Constructors

Throttler({required Duration duration, bool leading = true, bool trailing = true, Duration? maxWait})

Properties

duration Duration
节流间隔
final
hashCode int
The hash code for this object.
no setterinherited
isThrottled bool
当前是否处于节流中
no setter
leading bool
是否在首次调用时立即执行(leading edge)
final
maxWait Duration?
最大等待时间
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
trailing bool
是否在间隔结束后执行最后一次调用(trailing edge)
final

Methods

call(Future<T> action(), {bool? trailing}) Future<T>
执行节流包装后的异步函数
cancel() → void
取消待执行的节流尾调用
dispose() → void
释放资源
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
reset() → void
重置节流状态
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited