close
0

How to debounce Textfield onChange in Dart?

avatar
asked 13-09-2021

2 Answers


0

Debouncer class using Timer

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 it

final _debouncer = Debouncer(milliseconds: 500);

and trigger it

onTextChange(String text) {
  _debouncer.run(() => print(text));
}
avatar
answered 14-09-2021

0
final searchOnChange = new BehaviorSubject<String>();
...
TextField(onChanged: _search)
...

void _search(String queryString) {
  searchOnChange.add(queryString);
}   

void initState() {    
  searchOnChange.debounceTime(Duration(seconds: 1)).listen((queryString) { 
  >> request data from your API
  });
}
avatar
answered 14-09-2021