Home > Enterprise >  How to start a timer when a new page is opened in flutter?
How to start a timer when a new page is opened in flutter?

Time:05-18

I have to start an OTP auto fill timer as soon as the page is opened. What is method by which the timer can be started as soon as the page is opened?

CodePudding user response:

If you want your app to go back to previous view if the user could not enter the OTP before the time ends, you can use Tween builder inside your body content:

 TweenAnimationBuilder(
                                  tween: Tween(begin: 180.0, end: 0),
                                  duration: Duration(seconds: 180),
                                  builder: (context, value, child) {
                                    double val = value as double;
                                    int time = val.toInt();
                                    return Text(
                                      "Code Expires In $time"
                                        style: TextStyle(
                                        fontSize: FontConfig.appFontSize14,
                                        color: ColorUtils.greyText,
                                        fontWeight: FontWeight.w400,
                                      ),
                                    );
                                  },
                                  onEnd: () {
                                    Navigator.pop(context);
                                  },
                                ),

So, after 180 seconds the user will be sent back to previous screen.

or

If you are looking for a simple timer, just do the follow:

Timer? timer;

  @override
  void onInit() {
    super.onInit();

      timer = Timer.periodic(const Duration(seconds: 60), (Timer t) {
   
      print('TImer active');
    });

  }

  @override
  void dispose() {
    super.dispose();
    
    if(timer != null) {
      timer!.cancel();
    }
  }

use whichever fits your requirements

CodePudding user response:

First create a void function for the timer in stateful widget.

        void startTimer() {
  const onsec = Duration(seconds: 1);
  Timer timer = Timer.periodic(onsec, (timer) {
    if(start == 0 ) {
      setState(() {
        timer.cancel();
      });
      }else{
      setState(() {
        start--;
      });
    }
  });
}

Then call the function in override so the timer will start as soon as the page is opened

    @override
    void initState() {
    super.initState();
    startTimer();
    }
  • Related