'How to disable a button in flutter when a user click on it and a time is displayed instead?
I have a TextButton the code below:
TextButton(
onPressed: () {
sendAgainVerify();
},
child: Text(
'OK',
textAlign: TextAlign.center,
),
),
I want it to be disabled when the user click on it, and to be displayed for 1min (count down) instead of OK
This button is coded for this. When the code is not sent to the SMS user, the user clicks on it to send the code again.
void sendAgainVerify() async {
var response = await http.post(
Uri.parse(
"https://localhost/backend/api/v1/auth/mobile/confirm/resend"),
body: ({
"mobile": _mobileSeller,
}));
final body = jsonDecode(response.body);
if (response.statusCode == 200) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('${body['success']}')));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('${body['error']}')));
}
}
Solution 1:[1]
Try this:
import 'dart:async';
Timer _timer;
int _start = 60;
String _defaultText = 'OK';
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
const Duration(seconds: 1),
(Timer timer) {
if (_start == 0) {
setState(() {
timer.cancel();
_defaultText = 'OK';
});
} else {
setState(() {
_start--;
_defaultText = '$_start';
});
}
},
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
body:
TextButton(
onPressed: () {
startTimer();
sendAgainVerify();
},
child: Text(
_defaultText,
textAlign: TextAlign.center,
),
),
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jim |
