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

问题描述 投票:1回答:1

我想知道是否有一些我可能错过的内置功能。我试图找到类似的东西,但我发现的唯一包装(throttle)不再支持Dart 2

这是我想要限制的代码部分

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

有什么想法吗?

flutter dart-2
1个回答
1
投票

我会使用来自throttledebouncerxdart

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

也可以看看

© www.soinside.com 2019 - 2024. All rights reserved.