Debouncing and Throttling in Flutter using flutter_debouncer 2.0.0
Ever encountered moments when your app’s responsiveness didn’t quite match your expectations? Imagine you’re typing a message or clicking a button rapidly — your app can get overwhelmed trying to keep up, right? That’s where debouncing and throttling come to the rescue. We’ll walk you through a handy package called flutter_debouncer
that makes applying these techniques a breeze.
we’ll explain what debouncing and throttling really mean, and then show you how to use the flutter_debouncer
package with easy-to-follow examples. Say goodbye to unresponsive UI and glitchy behaviors – with this article, you'll be able to create apps that react just the way you want them to, delivering a smoother and more enjoyable user experience.
Debounce is a method used to control the firing of repetitive events by postponing their execution until a specified period of inactivity occurs. This prevents rapid or excessive triggering of events and is often employed to optimize performance and user experience in scenarios like search bars.
Imagine you have a search bar in your app that allows users to search for items in a database. As they type, the app initiates a query to fetch relevant results from the database. Without any control mechanism, every keystroke could trigger a new query, overwhelming the database and network with multiple requests in rapid succession. This could lead to performance issues, slow response times, and a less-than-optimal user experience.
This is where debouncing comes into play. Debouncing acts as a gatekeeper, delaying the execution of the query until the user pauses typing for a certain amount of time. For example, if the debounce time is set to 400 milliseconds, every time the user types a letter, the app will wait for 400 milliseconds of inactivity before sending the query. If the user continues typing within those 400 milliseconds, the countdown resets. This approach effectively prevents unnecessary multiple queries from being sent while the user is still actively typing.
flutter_debouncer
support optional type parameter, allowing developers to harness the flexibility of BehaviorType
for a wide array of use cases. BehaviorType.trailingEdge
will execute the callback after the specified time duration meanwhile, BehaviorType.leadingEdge
will execute the callback immediately and will not execute it back after the duration. BehaviorType.leadingAndTrailing
will execute the callback immediately and execute it again after the duration.
Throttle, on the other hand, limits the frequency of event execution by enforcing a fixed interval between successive executions. It ensures that events occur at a consistent rate, preventing resource overuse and maintaining smooth performance. Throttling is commonly used for tasks like scrolling, mouse movement tracking, and managing API requests.
Imagine a scenario involving a webpage where users can scroll through a lengthy article or a list of items. As users scroll, a series of scroll events are triggered. Without any control mechanism, these frequent events could potentially overwhelm the system and cause performance issues. This is where throttle steps in to provide a solution.
By applying throttle to the scroll event, you create a measured cadence for handling these events. For example, let’s say you’ve set a throttle interval of 400 milliseconds. As users scroll, the scroll event will be processed only once every 400 milliseconds, regardless of how quickly they scroll. This prevents the system from becoming inundated with an excessive number of scroll events and ensures that the scrolling experience remains smooth and responsive.
Imagine a scenario involving a webpage where users can scroll through a lengthy article or a list of items. As users scroll, a series of scroll events are triggered. Without any control mechanism, these frequent events could potentially overwhelm the system and cause performance issues. This is where throttle steps in to provide a solution.
Just like debounce
throttle in flutter_debouncer
also supports type parameter of BehaviorType
so you can either use BehaviorType.trailingEdge
, BehaviorType.leadingEdge
, orBehaviorType.leadingAndTrailing.
How to use flutter_debouncer 2.0.0
Step 1: Addflutter_debouncer
into your pubspec.yaml
dependencies:
flutter_debouncer: 2.0.0
Step 2: Import theflutter_debouncer
package
import 'package:flutter_debouncer/flutter_debouncer.dart';
Step 3: Initialize Debouncer or Throttler Service
final Debouncer _debouncer = Debouncer();
final Throttle _throttler = Throttler();
Step 4: Call the debounce/throttle method through the instance
Debounce:
void _handleTextFieldChange(String value) {
const duration = Duration(milliseconds: 500);
_debouncer.debounce(
duration: duration,
onDebounce: () {
setState(() {
debouncedText = value;
});
},
);
}
Throttle:
void _handleTextFieldChange(String value) {
const duration = Duration(milliseconds: 500);
_throttler.throttle(
duration: duration,
onThrottle: () {
setState(() {
throttledCounter++;
});
},
);
}
Use type
parameter to pass BehaviorType
to change the behavior of the debounce or throttle:
void _handleTextFieldChange(String value) {
const duration = Duration(milliseconds: 500);
/// - [BehaviorType.leadingEdge] : The callback function is executed immediately
_debouncer.debounce(
duration: duration,
type: BehaviorType.leadingEdge,
onDebounce: () {
setState(() {
debouncedText = value;
});
},
);
}
You can also cancel the debouncer or throttle method manually by using the cancel method on debouncer/throttle service
///Debouncer Cancel
_debouncer.cancel();
///Throttler Cancel
_throttler.cancel();
To wrap up our exploration of debouncing and throttling, we’ve uncovered two invaluable techniques that wield significant influence over event management. These strategies, when harnessed effectively through tools like the flutter_debouncer
package, provide developers with a dynamic range of solutions to enhance user experiences and optimize system performance.