Created
July 15, 2024 14:29
-
-
Save lopo12123/22f5d704818557dd5caf9938aee9670e to your computer and use it in GitHub Desktop.
BadFL Example Code (helper/debounce)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
class BadDebouncer { | |
final Duration delay; | |
/// default action to be called when the debouncer is called without a action | |
final void Function()? defaultAction; | |
Timer? _timer; | |
BadDebouncer({this.delay = const Duration(seconds: 1), this.defaultAction}); | |
void call([void Function()? action]) { | |
assert( | |
action != null || defaultAction != null, | |
'can only call debouncer without action when defaultAction is provided', | |
); | |
_timer?.cancel(); | |
_timer = Timer(delay, (action ?? defaultAction)!); | |
} | |
/// cancel the current delayed call | |
void cancel() => _timer?.cancel(); | |
} | |
void main() async { | |
final debouncer = BadDebouncer( | |
delay: const Duration(seconds: 1), | |
defaultAction: () { | |
print('default action'); | |
}, | |
); | |
// 1. call the default action | |
debouncer(); | |
// 2. call with a custom action | |
await Future.delayed(const Duration(seconds: 2)); | |
debouncer.call(() { | |
print('wrong action'); | |
}); | |
// 3. cancel the current delayed call | |
debouncer.cancel(); | |
debouncer(() { | |
print('correct action'); | |
}); | |
} | |
// Output: | |
// default action | |
// correct action |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment