Skip to content

Instantly share code, notes, and snippets.

@rodrigofelipejr
Created November 5, 2021 20:08
Show Gist options
  • Select an option

  • Save rodrigofelipejr/d00d71ee6ae6c53a401ff8de2aefc623 to your computer and use it in GitHub Desktop.

Select an option

Save rodrigofelipejr/d00d71ee6ae6c53a401ff8de2aefc623 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:flutter/material.dart';
class DebouncedButtonWidget extends StatefulWidget {
final String label;
final void Function()? onPressed;
const DebouncedButtonWidget({
Key? key,
required this.label,
this.onPressed,
}) : super(key: key);
@override
_DebouncedButtonWidgetState createState() => _DebouncedButtonWidgetState();
}
class _DebouncedButtonWidgetState extends State<DebouncedButtonWidget> {
late ValueNotifier<bool> _isEnabled;
Timer? _timer;
@override
void initState() {
super.initState();
_isEnabled = ValueNotifier<bool>(true);
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void Function()? get _onButtonPressed => (widget.onPressed != null)
? () {
_isEnabled.value = false;
_timer = Timer(const Duration(milliseconds: 500), () {
_isEnabled.value = true;
});
widget.onPressed!();
}
: null;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: _isEnabled,
builder: (_, isEnabled, __) {
return ElevatedButton(
onPressed: isEnabled ? _onButtonPressed : null,
child: Text(widget.label),
);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment