How to debounce Textfield onChange in Dart?

CodeWithFlutter
1 Min Read

Debouncing is a technique that is commonly used to avoid excessive processing when handling events that are fired rapidly, such as a user typing in a text field. You can implement debouncing in Dart using the Timer class. Here’s a simple example:

import 'dart:async';

class Debouncer {
  final int milliseconds;
  VoidCallback action;
  Timer _timer;

  Debouncer({this.milliseconds});

  run(VoidCallback action) {
    if (_timer != null) {
      _timer.cancel();
    }
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}

You can use the Debouncer class in your text field onChanged event like this:

final debouncer = Debouncer(milliseconds: 500);

TextField(
  onChanged: (value) {
    debouncer.run(() {
      // Do expensive work here
    });
  },
)

In this example, the Debouncer class will wait 500 milliseconds after the last change event before calling the action function. If another change event occurs within that 500 milliseconds, the previous action will be cancelled and a new timer will be started.

Share this Article
Leave a comment