如何在Dart 2中限制TextEditingController侦听器事件-Flutter

时间:2019-01-22 20:19:50

标签: flutter dart-2

我想知道是否有一些内置函数可能会错过。我试图找到类似的东西,但Dart 2不再支持我找到的唯一软件包(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);
    });

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我将使用throttle中的debouncerxdart

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);
});

另请参见