I have a button and it should appear in 30 seconds. The countdown starts from 30 seconds. When it reaches 0, the resend code button should appear/enable.
I have a button and it should appear in 30 seconds. The countdown starts from 30 seconds. When it reaches 0, the resend code button should appear/enable.
You can do it like this using Timer from dart:async..
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int secondsRemaining = 30;
bool enableResend = false;
Timer timer;
@override
initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (_) {
if (secondsRemaining != 0) {
setState(() {
secondsRemaining--;
});
} else {
setState(() {
enableResend = true;
});
}
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(),
const SizedBox(height: 10),
FlatButton(
child: Text('Submit'),
color: Colors.blue,
onPressed: () {
//submission code here
},
),
const SizedBox(height: 30),
FlatButton(
child: Text('Resend Code'),
onPressed: enableResend ? _resendCode : null,
),
Text(
'after $secondsRemaining seconds',
style: TextStyle(color: Colors.white, fontSize: 10),
),
],
);
}
void _resendCode() {
//other code here
setState((){
secondsRemaining = 30;
enableResend = false;
});
}
@override
dispose(){
timer.cancel();
super.dispose();
}
}
Link to the code on Dartpad - https://dartpad.dev/a59c751c4f6b4721a7af1cc27c67650b
For someone searching for this solution for new Versions of Flutter, which has null safety. You need to make some changes to the verified code shared by Jigar Patel above.
Reason: adding ? will help you to bypass null safety.
Now coming to use Resend OTP Functionality
I've arranged two containers in a Column, first Container for Resend OTP Button and second Container to show timer like this:
Column ( children:[
Container( width: 150, margin: EdgeInsets.only( left: 410, ), child: InkWell( onTap: () => enableResend ? _resendCode() : null, child: Text( "Resend OTP", style: TextStyle( fontSize: 13, color: enableResend ? Color(0xff3E64FF) : Colors.grey, fontWeight: FontWeight.bold, fontFamily:'Raleway'), ), ), ),
const SizedBox( height: 5, ), Container( width: 150, margin: EdgeInsets.only( left: 390, ), child: InkWell( child: Text( '(after $secondsRemaining seconds)', style: TextStyle( color: Color(0xff3E64FF), fontSize: 10), ), ), ),
], ),
so here with respect to Jigar Patel's code, I've changed:
3)_resendCode() instead of just using _resendCode, because on clicking resend button function should be called.
onTap: () => enableResend ? _resendCode() : null,
void _resendCode() { //other code here SendCodeOnEmail (); setState(() { secondsRemaining = 30; enableResend = false; }); }
so that Resend OTP text is disabled for 30 seconds and it's colour changes to grey, and when it is enabled it changes to blue