52 lines
1.3 KiB
Dart
52 lines
1.3 KiB
Dart
// debounce.dart
|
|
|
|
import 'dart:async';
|
|
|
|
import 'package:easy_debounce/easy_throttle.dart';
|
|
import 'package:flutter/material.dart';
|
|
|
|
/// 函数防抖
|
|
///
|
|
/// [func]: 要执行的方法
|
|
/// [delay]: 要迟延的时长
|
|
VoidCallback debounce(Function func, [Duration delay = const Duration(milliseconds: 2000)]) {
|
|
Timer? timer;
|
|
VoidCallback target = () {
|
|
if (timer?.isActive ?? false) {
|
|
timer?.cancel();
|
|
}
|
|
timer = Timer(delay, () {
|
|
func.call();
|
|
});
|
|
};
|
|
return target;
|
|
}
|
|
|
|
/// 函数节流
|
|
///
|
|
/// [func]: 要执行的方法
|
|
VoidCallback throttle(Future Function() func) {
|
|
bool enable = true;
|
|
VoidCallback target = () {
|
|
if (enable == true) {
|
|
enable = false;
|
|
func().whenComplete(() {
|
|
enable = true;
|
|
});
|
|
}
|
|
};
|
|
return target;
|
|
}
|
|
|
|
/// 函数节流
|
|
///
|
|
/// [func]: 要执行的方法
|
|
bool easyThrottle(String tagId,EasyThrottleCallback onExecute, {Duration duration = const Duration(milliseconds: 300),EasyThrottleCallback? onAfter}) {
|
|
return EasyThrottle.throttle(
|
|
tagId, // <-- An ID for this particular throttler
|
|
duration, // <-- The throttle duration
|
|
onExecute, // <-- The target method
|
|
onAfter:onAfter // <-- Optional callback, called after the duration has passed
|
|
);
|
|
}
|