3

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?

Victor Hugo Montes
  • 1,270
  • 1
  • 17
  • 28

1 Answers1

5

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Worked like a charm @@Günter Zöchbauer. Many thanks. However, just one correction the line **_filter.addListener(() => _textUpdates(_filter.text));** complains that it is not a **Function**. Then I change to **_filter.addListener(() => _textUpdates.add(_filter.text));** I'd suggest you to update the answer. Other than that, all good! – Victor Hugo Montes Jan 23 '19 at 13:18
  • 2
    Thanks - fixed. Writing code without an IDE is always a bit of a challenge :D – Günter Zöchbauer Jan 23 '19 at 13:24