Skip to content

Latest commit

 

History

History
209 lines (140 loc) · 5.05 KB

File metadata and controls

209 lines (140 loc) · 5.05 KB

Debouncing in Flutter

When building a "search-as-you-type" feature, you need to strike the right balance between two things:

  • show the results quickly
  • avoid excessive calls to the server API

This can be accomplished with a so-called debouncer.

Here's a thread showing how to implement this. 🧵


Debouncing with Timer

The simplest debouncer you can build uses a simple Timer.

It works with a timer that triggers a callback, but only if a given duration has elapsed since the previous invocation. 👇


Debouncing with Timer: Usage

To use this debouncer, declare it inside a widget class.

Then, from a TextField onChanged callback, you can call a method that runs the debouncer.


Debouncing with ValueNotifier

A more flexible solution is to turn the debouncer into an observable class, such as a ValueNotifier.

This makes it easier to observe the debouncer with a ValueListenableBuilder that lives elsewhere in the widget tree.


Debouncing with Riverpod Notifier

Here's another example using Riverpod.

In this case, the debouncer is a Notifier subclass where:

  • the build method returns the initial query (an empty string)
  • the timer is created in the setQuery method
  • the timer is cancelled as needed


Debouncing with Notifier: Usage

The advantage over the ValueNotifier implementation is that with Riverpod, we can listen to the notifier inside a separate provider.

This makes it easier to lift the fetching logic outside our widget code.


Debouncing with EasyDebounce

For more flexibility and control, you can use the easy_debounce package.

This allows you to create multiple debouncers indexed by key and offers three variants:

  • EasyDebounce
  • EasyThrottle
  • EasyRateLimit

Check the package README for how to use them.


When building a search UX for your app, the debouncer is a small but important piece of the puzzle.

To learn about how to build a complete search feature with pagination, read this article: 👇


Found this useful? Show some love and share the original tweet


Previous Next
Null-aware spread operator (...?) Force App Upgrade Gone Wrong 😭