Flutter 中可以通过使用 debounce 方法来实现防抖操作。debounce 方法的作用是在一定时间内只执行一次函数,可以避免频繁的请求或操作。

例如,在一个 TextField 中输入文字时,我们希望用户输入完成后才执行搜索操作,可以在 textEditingController 的监听器中使用 debounce 方法来实现:

final TextEditingController _controller = TextEditingController();
Timer _debounce;

void _onSearchTextChanged(String text) {
  if (_debounce?.isActive ?? false) _debounce.cancel();
  _debounce = Timer(const Duration(milliseconds: 500), () {
    // 执行搜索操作
  });
}

@override
void initState() {
  super.initState();
  _controller.addListener(() => _onSearchTextChanged(_controller.text));
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

_onSearchTextChanged 方法中,我们使用了 Timer 来延迟执行搜索操作,如果在 500 毫秒内用户继续输入,就会取消之前的延迟执行操作,重新延迟执行新的操作,以此来达到防抖的效果。需要注意的是,使用完 Timer 后需要将其 cancel 掉,否则会造成内存泄漏。

Flutter TextField 防抖:提高用户体验的最佳实践

原文地址: https://www.cveoy.top/t/topic/m2Ke 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录