Line data Source code
1 : import 'dart:async';
2 : import 'package:flutter/foundation.dart';
3 : import '../debouncer_config.dart';
4 : import 'debounce_strategy.dart';
5 :
6 : /// Fires the action immediately on the **first** call, then ignores
7 : /// subsequent calls until [DebouncerConfig.delay] has elapsed.
8 : ///
9 : /// Ideal for button clicks and submit actions where you want instant
10 : /// feedback but need to prevent accidental double-submission.
11 : ///
12 : /// Timeline:
13 : /// ```
14 : /// calls: --A--B--C-----------
15 : /// fires: --A
16 : /// ```
17 : class LeadingEdgeStrategy extends DebouncerStrategy {
18 1 : const LeadingEdgeStrategy();
19 :
20 1 : @override
21 : void execute(
22 : VoidCallback action,
23 : DebouncerConfig config,
24 : Timer? currentTimer,
25 : void Function(Timer?) updateTimer,
26 : ) {
27 1 : final isIdle = currentTimer == null || !currentTimer.isActive;
28 1 : currentTimer?.cancel();
29 :
30 : // Schedule a cooldown timer (action won't fire again until this expires).
31 5 : updateTimer(Timer(config.delay, () => updateTimer(null)));
32 :
33 : if (isIdle) {
34 1 : action();
35 : }
36 : }
37 : }
|