Victor Hugo Montes
Victor Hugo Montes

Reputation: 1322

How to throttle TextEditingController listener events in Dart 2 - Flutter

I am wondering if there's some built in function that I might have missed. I tried to find something similar, but the only package I found (throttle) is not supported for Dart 2 anymore

Here's the part of the code I wanted to throttle

final TextEditingController _filter = new TextEditingController();
String _searchText = "";

_filter.addListener(() {
      if (_filter.text.isEmpty) {
        setState(() {
          _searchText = "";
        });
      } else {
        setState(() {
          _searchText = _filter.text;
        });
      }
      //This action is being fired TOO many times :(
      widget.onUpdateSearchTerm(_searchText);
    });

Any ideas on that?

Upvotes: 3

Views: 3456

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657376

I'd use throttle or debounce from rxdart

on rxdart 0.22.x using Observable

final TextEditingController _filter = new TextEditingController();
String _searchText = "";
final _textUpdates = StreamController<String>();

_filter.addListener(() => _textUpdates.add(_filter.text));

Observable(_textUpdates.stream)
.throttle(const Duration(milliseconds: 700))
.forEach((s) {
  if (s.isEmpty) {
    setState(() {
      _searchText = "";
    });
  } else {
    setState(() {
      _searchText = s;
    });
  }
  //This action is being fired TOO many times :(
  widget.onUpdateSearchTerm(_searchText);
});

on rxdart 0.23.x and onwards

final TextEditingController _filter = new TextEditingController();
String _searchText = "";
final _textUpdates = StreamController<String>();

_filter.addListener(() => _textUpdates.add(_filter.text));

_textUpdates.stream
.throttle(const Duration(milliseconds: 700))
.forEach((s) {
  if (s.isEmpty) {
    setState(() {
      _searchText = "";
    });
  } else {
    setState(() {
      _searchText = s;
    });
  }
  //This action is being fired TOO many times :(
  widget.onUpdateSearchTerm(_searchText);
});

See also

Upvotes: 5

Related Questions