click.dart 919 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import 'dart:async';
  2. import 'package:flutter/widgets.dart';
  3. ValueChanged debounceValueChanged(ValueChanged fn, [int t = 500]) {
  4. Timer _debounce;
  5. return (value) {
  6. // 还在时间之内,抛弃上一次
  7. if (_debounce?.isActive ?? false) _debounce.cancel();
  8. _debounce = Timer(Duration(milliseconds: t), () {
  9. fn(value);
  10. });
  11. };
  12. }
  13. Function debounce(
  14. Function func, [
  15. Duration delay = const Duration(milliseconds: 2000),
  16. ]) {
  17. Timer timer;
  18. Function target = () {
  19. if (timer?.isActive ?? false) {
  20. timer?.cancel();
  21. }
  22. timer = Timer(delay, () {
  23. func?.call();
  24. });
  25. };
  26. return target;
  27. }
  28. Function throttle(
  29. Future Function() func,
  30. ) {
  31. if (func == null) {
  32. return func;
  33. }
  34. bool enable = true;
  35. Function target = () {
  36. if (enable == true) {
  37. enable = false;
  38. func().then((_) {
  39. enable = true;
  40. });
  41. }
  42. };
  43. return target;
  44. }