click.dart 887 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. bool enable = true;
  32. Function() target = () {
  33. if (enable == true) {
  34. enable = false;
  35. func().then((_) {
  36. enable = true;
  37. });
  38. }
  39. };
  40. return target;
  41. }