Line data Source code
1 : import 'debouncer.dart';
2 : import 'strategy/debounce_strategy.dart';
3 : import 'strategy/trailing_edge_strategy.dart';
4 : import 'utils/debouncer_logger.dart';
5 :
6 : /// Extension on [Function] to create debounced versions directly.
7 : ///
8 : /// This is a convenience wrapper — under the hood it creates a [Debouncer]
9 : /// and returns a new function that calls [Debouncer.run].
10 : ///
11 : /// **Important**: The returned function holds a [Debouncer] internally.
12 : /// For proper cleanup in long-lived objects, prefer creating an explicit
13 : /// [Debouncer] and calling [Debouncer.dispose] in your [State.dispose].
14 : ///
15 : /// ## Usage
16 : /// ```dart
17 : /// final debouncedSearch = _search.debounced(
18 : /// delay: Duration(milliseconds: 300),
19 : /// );
20 : ///
21 : /// // Later:
22 : /// debouncedSearch();
23 : /// ```
24 : extension DebouncedFunction on void Function() {
25 : /// Returns a debounced version of this function.
26 : ///
27 : /// Each call to the returned function resets the timer.
28 : /// The original function fires once the [delay] elapses.
29 1 : void Function() debounced({
30 : Duration delay = const Duration(milliseconds: 300),
31 : DebouncerStrategy strategy = const TrailingEdgeStrategy(),
32 : DebouncerLogger? logger,
33 : }) {
34 1 : final debouncer = Debouncer(
35 : delay: delay,
36 : strategy: strategy,
37 : logger: logger,
38 : );
39 2 : return () => debouncer.run(this);
40 : }
41 : }
42 :
43 : /// Extension on single-argument functions for debounced use.
44 : ///
45 : /// ```dart
46 : /// final debouncedOnChanged = _onChanged.debounced(
47 : /// delay: Duration(milliseconds: 400),
48 : /// );
49 : ///
50 : /// TextField(onChanged: debouncedOnChanged)
51 : /// ```
52 : extension DebouncedFunction1<A> on void Function(A) {
53 : /// Returns a debounced version of this single-argument function.
54 1 : void Function(A) debounced({
55 : Duration delay = const Duration(milliseconds: 300),
56 : DebouncerStrategy strategy = const TrailingEdgeStrategy(),
57 : DebouncerLogger? logger,
58 : }) {
59 : A? lastArg;
60 1 : final debouncer = Debouncer(
61 : delay: delay,
62 : strategy: strategy,
63 : logger: logger,
64 : );
65 1 : return (A arg) {
66 : lastArg = arg;
67 3 : debouncer.run(() => this(lastArg as A));
68 : };
69 : }
70 : }
|