Skip to content

Instantly share code, notes, and snippets.

@lopo12123
Created July 15, 2024 14:29
Show Gist options
  • Save lopo12123/22f5d704818557dd5caf9938aee9670e to your computer and use it in GitHub Desktop.
Save lopo12123/22f5d704818557dd5caf9938aee9670e to your computer and use it in GitHub Desktop.
BadFL Example Code (helper/debounce)
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