How to debounce action in Flutter

Issue #293

Answer https://stackoverflow.com/a/55119208/1418457


This is useful to throttle TextField change event. You can make Debouncer class using Timer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'package:flutter/foundation.dart';
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);
}
}

Declare and trigger

1
2
3
4
5
final _debouncer = Debouncer(milliseconds: 500);

onTextChange(String text) {
_debouncer.run(() => print(text));
}

Comments