How to enable/disable a button ("resend code" button for phone verification) in relation to a countdown timer?

Issue

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.

enter image description here

Solution

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

Answered By – Jigar Patel

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *