popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.
3 stars 0 forks source link

Debounce action in Flutter #24

Open popeyelau opened 4 years ago

popeyelau commented 4 years ago
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);
  }
}

trigger

final _debouncer = Debouncer(milliseconds: 500);

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