How to debounce Textfield onChange in Dart?

后端 未结 9 1188
攒了一身酷
攒了一身酷 2020-12-03 04:49

I\'m trying to develop a TextField that update the data on a Firestore database when they change. It seems to work but I need to prevent the onChange event to fire multiple

9条回答
  •  -上瘾入骨i
    2020-12-03 05:13

    In your widget state declare a controler and timer:

    final _searchQuery = new TextEditingController();
    Timer _debounce;
    

    Add a listener method:

    _onSearchChanged() {
        if (_debounce?.isActive ?? false) _debounce.cancel();
        _debounce = Timer(const Duration(milliseconds: 500), () {
            // do something with _searchQuery.text
        });
    }
    

    Hook and un-hook the method to the controller:

    @override
    void initState() {
        super.initState();
        _searchQuery.addListener(_onSearchChanged);
    }
    
    @override
    void dispose() {
        _searchQuery.removeListener(_onSearchChanged);
        _searchQuery.dispose();
        _debounce?.cancel();
        super.dispose();
    }
    

    In your build tree bind the controller to the TextField:

    child: TextField(
            controller: _searchQuery,
            // ...
        )
    

提交回复
热议问题