Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active September 14, 2021 04:55
Show Gist options
  • Save Klerith/8196f719201419bc09cd684982097896 to your computer and use it in GitHub Desktop.
Save Klerith/8196f719201419bc09cd684982097896 to your computer and use it in GitHub Desktop.
Dart: Debouncer
import 'dart:async';
// Creditos
// https://stackoverflow.com/a/52922130/7834829
class Debouncer<T> {
Debouncer({
required this.duration,
this.onValue
});
final Duration duration;
void Function(T value)? onValue;
T? _value;
Timer? _timer;
T get value => _value!;
set value(T val) {
_value = val;
_timer?.cancel();
_timer = Timer(duration, () => onValue!(_value!));
}
}
// final debouncer = Debouncer<String>(duration: Duration(milliseconds: 500 ));
void getSugerenciasPorQuery( String busqueda, LatLng proximidad ) {
debouncer.value = '';
debouncer.onValue = ( value ) async {
final resultados = await this.getResultadosPorQuery(value, proximidad);
this._sugerenciasStreamController.add(resultados);
};
final timer = Timer.periodic(Duration(milliseconds: 200), (_) {
debouncer.value = busqueda;
});
Future.delayed(Duration(milliseconds: 201)).then((_) => timer.cancel());
}
@EduardinDev
Copy link

Gracias profe, funciona excelente!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment