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?
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