Skip to content

Instantly share code, notes, and snippets.

@denesh-raymond
Created November 28, 2020 01:06
Show Gist options
  • Save denesh-raymond/1a9e84a550f4015075e4936469a1b19e to your computer and use it in GitHub Desktop.
Save denesh-raymond/1a9e84a550f4015075e4936469a1b19e to your computer and use it in GitHub Desktop.
Debounced Button in Flutter
import 'dart:async';
import 'package:flutter/material.dart';
class DebouncedButton extends StatefulWidget {
final String _text;
final VoidCallback _onPressed;
final Duration _duration;
DebouncedButton({
@required String text,
@required VoidCallback onPressed,
int debounceTimeMs = 200,
}) : this._text = text,
this._onPressed = onPressed,
this._duration = Duration(milliseconds: debounceTimeMs);
@override
_DebouncedButtonState createState() => _DebouncedButtonState();
}
class _DebouncedButtonState extends State<DebouncedButton> {
ValueNotifier<bool> _isEnabled;
Timer _timer;
@override
void initState() {
super.initState();
_isEnabled = ValueNotifier<bool>(true);
}
@override
void dispose() {
super.dispose();
_timer?.cancel();
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: _isEnabled,
builder: (context, isEnabled, child) => ElevatedButton(
onPressed: isEnabled ? _onButtonPressed : null,
child: Text(widget._text),
),
);
}
void _onButtonPressed() {
_isEnabled.value = false;
widget._onPressed();
_timer = Timer(widget._duration, () => _isEnabled.value = true);
}
}
@FrizzleFur
Copy link

I think on onPressed,( line 43) if isEnabled is false, need cancel _timer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment