MyurA
MyurA

Reputation: 15

How to reset countdown in Flutter

I'm make some apps that can resend some otp when I tap "Resend". I'm trying to refresh state but it seems didn't work. Can someone help with how to reset that countdown timer?

Dartpad Code

Upvotes: 0

Views: 1505

Answers (2)

NewbiewDev
NewbiewDev

Reputation: 212

You need to pass the function

first you need to change your restartTimer to this

   void restartTimer() {
    setState(() {
      _controller.reset();
       _controller.forward();
    });
  }

then change the widget that use Countdown to this

  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Countdown(
            restartTimer:restartTimer, // send the function
            animation: StepTween(
              begin: 1 * 60,
              end: 0,
            ).animate(_controller),
          ),
        ),
      ),
    );
  }

After that you need to receive the function

class Countdown extends AnimatedWidget {
  Countdown({Key key, this.animation,this.restartTimer}) : super(key: key, listenable: animation);
  Animation<int> animation;
  final Function restartTimer;
   ....

then inside the Countdown change the OnTap to this

 onTap: () {
              this.restartTimer();
            },

Upvotes: 1

Try this

void restartTimer() {
    countDownTimer.cancel();
    startTimer();
  }

Upvotes: 0

Related Questions