Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Restart CountdownTimer

Tags:

flutter

I have a countdown timer (5 mins). I need something to restart this countdown and start from the beginning.

I try to change state of countdown variable but doesn´t works, stops and restarting from the last number of counter.

My code:

import 'package:flutter/material.dart';
    import 'package:intl/intl.dart';
    import 'package:quiver/async.dart';

    class ProgressIndicatorDemo extends StatefulWidget {
      @override
      _ProgressIndicatorDemoState createState() =>
          new _ProgressIndicatorDemoState();
    }

    class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo>
        with SingleTickerProviderStateMixin {
      AnimationController controller;
      Animation<double> animation;
      var countdown;
      int actual;

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

      @override
      void dispose() {
        controller.dispose();
        super.dispose();
      }

      void animationStart() {
        controller =
            AnimationController(duration: Duration(minutes: 5), vsync: this);
        animation = Tween(begin: 0.0, end: 1.0).animate(controller)
          ..addListener(() {
            setState(() {});
          });
        controller.forward();
      }

      void startTimer() {
        CountdownTimer countDownTimer = new CountdownTimer(
          new Duration(minutes: 5),
          new Duration(seconds: 1),
        );

        countdown = countDownTimer.listen(null);
        countdown.onData((duration) {
          setState(() {
            actual = 300 - duration.elapsed.inSeconds;
          });
        });

        countdown.onDone(() {
          countdown.cancel();
        });
      }

      @override
      Widget build(BuildContext context) {
        return new Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              animation.value != 1.0
                  ? CircularProgressIndicator(
                      semanticsLabel:
                          (animation.value * 100.0).toStringAsFixed(1).toString() +
                              '%',
                      semanticsValue:
                          (animation.value * 100.0).toStringAsFixed(1).toString() +
                              '%',
                      backgroundColor: Colors.black.withOpacity(0.25),
                      valueColor:
                          new AlwaysStoppedAnimation<Color>(Colors.green[700]),
                      value: animation.value)
                  : Icon(Icons.info_outline),
              actual != null
                  ? Text(
                      "Tiempo:" +
                          DateFormat.ms()
                              .format(DateTime.fromMillisecondsSinceEpoch(
                                  actual * 1000))
                              .toString(),
                      textAlign: TextAlign.center,
                    )
                  : Container(),
              FlatButton(
                  child: Text('Reset ' + actual.toString()), onPressed: () {}),
            ],
          ),
        );
      }
    }

So the question is: How can i restart from the beggining the countdown?

like image 642
El Hombre Sin Nombre Avatar asked Dec 18 '22 17:12

El Hombre Sin Nombre


2 Answers

You could use a cleaner solution by using the RestartableTimer

import 'package:async/async.dart';

RestartableTimer _timer = new RestartableTimer(_timerDuration, _startNewPage);

Then you can restart your countdown by simply calling _timer.reset();

Hope it helps.

like image 164
Felipe Campos Avatar answered Dec 20 '22 06:12

Felipe Campos


Try cancel the timer first and start the timer again :

  void restartTimer() {
    countDownTimer.cancel();
    startTimer();
  }
like image 29
diegoveloper Avatar answered Dec 20 '22 05:12

diegoveloper