过滤ListView,延迟搜索,查找,消除抖动和飞镖

时间:2019-09-16 04:37:34

标签: flutter

我是新手,找不到我想要的解决方案。

我有一个文本字段,我想在几秒钟后在列表中搜索产品代码,并在列表视图中显示与该代码匹配的产品。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

尝试一下。

    void main() {
    runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
    final TextEditingController controller = TextEditingController();

    final Debouncer onSearchDebouncer =
        new Debouncer(delay: new Duration(milliseconds: 500));

    @override
    Widget build(BuildContext context) {
        return MaterialApp(
        home: Scaffold(
            backgroundColor: Colors.white,
            body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Center(
                child: TextField(
                    controller: this.controller,
                    onChanged: (val) => this.onSearchDebouncer.debounce(
                        () => print("text : " + val),
                        )),
            ),
            ),
        ),
        );
    }
    }

带有计时器的自定义Debouncer类。

        import 'dart:async';
        import 'dart:ui';

        class Debouncer {
        Duration delay;
        Timer _timer;
        VoidCallback _callback;

        Debouncer({this.delay = const Duration(milliseconds: 500)});

        void debounce(VoidCallback callback) {
            this._callback = callback;

            this.cancel();
            _timer = new Timer(delay, this.flush);
        }

        void cancel() {
            if (_timer != null) {
            _timer.cancel();
            }
        }

        void flush() {
            this._callback();
            this.cancel();
        }
        }