Debounce constructor
Debounce is used to control the frequency of function calls with support for flexible delay and "leading" / "trailing" options.
This class is especially useful when you need to prevent frequent repeated calls:
- when entering text (for example, search)
- when processing scroll events
- when using resize handlers
- when pressing buttons (for example, double-click protection)
Supports:
- delay — How long to wait after the last call before executing
- leading — If
true
,callback
will be called on the first call before the interval expires. - trailing — If
true
,callback
will be called after the interval ends - leading && trailing If both are
true
, leadingcallback
will be called immediately before the interval expires and trailingcallback
will be called after the interval ends (if there were repeated calls)
Usage example:
final _debounce = Debounce(delay: Duration(seconds: 1), leading: false, trailing: true); ✅ Good!
Config: leading: false, trailing: true
Input: 1-2-3---4---5-6-|
Output: ------3---4-----6|
final _debounce = Debounce(delay: Duration(seconds: 1), leading: true, trailing: false); ✅ Good!
Config: leading: true, trailing: false
Input: 1-2-3---4---5-6-|
Output: 1-------4---5---|
final _debounce = Debounce(delay: Duration(seconds: 1), leading: true, trailing: true); ✅ Good!
Config: leading: true, trailing: true
Input: 1-2-3---4---5-6-|
Output: 1-----3-4---5---6|
final _debounce = Debounce(delay: Duration(seconds: 1), leading: false, trailing: false); ❌ Bad! Output empty!
Config: leading: false, trailing: false
Input: 1-2-3---4---5-6-|
Output: ----------------|
final _debounce = Debounce(delay: Duration(milliseconds: 500));
void onTextChanged(String text) {
_debounce(() {
// ...
});
}
@override
void dispose() {
_debounce.dispose();
super.dispose();
}
Implementation
Debounce({this.delay = defaultDelay, this.leading = false, this.trailing = true})
: assert(!delay.isNegative, '❌ [Bad] [Duration] delay must be positive!') {
/*
// We bind the finalizer to the [Debounce] object at the time of its creation.
//
// When the object is no longer in use (for example, it will be deleted by 'Garbage collectors'), the [_finalizer] will automatically call [dispose] for the [Debounce] object.
_finalizer.attach(this, this, detach: this);
*/
}