How to debounce Textfield onChange in Dart?

后端 未结 9 1211
攒了一身酷
攒了一身酷 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条回答
  •  生来不讨喜
    2020-12-03 05:03

    You can make Debouncer class using Timer

    import 'package:flutter/foundation.dart';
    import 'dart:async';
    
    class Debouncer {
      final int milliseconds;
      VoidCallback action;
      Timer _timer;
    
      Debouncer({ this.milliseconds });
    
      run(VoidCallback action) {
        if (_timer != null) {
          _timer.cancel();
        }
    
        _timer = Timer(Duration(milliseconds: milliseconds), action);
      }
    }
    

    Declare it

    final _debouncer = Debouncer(milliseconds: 500);
    

    and trigger it

    onTextChange(String text) {
      _debouncer.run(() => print(text));
    }
    

提交回复
热议问题