How to debounce Textfield onChange in Dart?

Implementation

Import dependencies:

import 'dart:async';

In your widget state declare a timer:

Timer? _debounce;

Add a listener method:

_onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
        // do something with query
    });
    }

Don’t forget to clean up:

@override
void dispose() {
    _debounce?.cancel();
    super.dispose();
}

Usage

In your build tree hook the onChanged event:

child: TextField(
        onChanged: _onSearchChanged,
        // ...
    )

Leave a Comment

tech