0

I'm looking for the best way to make a countdown timer in Flutter. I made it this way, but i'm not sure this efficient way to do it, this is my code :

class CountDown extends StatefulWidget {
  final int secondsNum;
  CountDown({Key key, @required this.secondsNum}) : super(key: key);
  @override
  _CountDownState createState() => _CountDownState(secondsNum);
}
class _CountDownState extends State<CountDown> {
  Timer _timer;
  int _start;
  _CountDownState(int start) {
    this._start = start;
    startTimer();
  }
  void startTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = new Timer.periodic(
        oneSec,
            (Timer timer) => setState(() {
          if (_start < 1) {
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        })
    );
  }
  @override
  Widget build(BuildContext context) {
    return Text("$_start");
  }
  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }
}

And then import that file and call it this way: CountDown(secondsNum: 50). The problem is that I'm going to call CountDown(secondsNum: 50) like 10 times in the same screen.

There are a lot of Javascript libraries that can do the same thing for Web, but I didn't find any for Flutter so far. If anyone has an idea about the best way to do this, please post it below. Thanks in advance.

KeroppiMomo
  • 564
  • 6
  • 18
ler
  • 1,466
  • 3
  • 20
  • 37
  • why don't u used [CountdownTimer class](https://docs.flutter.io/flutter/quiver.async/CountdownTimer-class.html)? – flix Apr 10 '19 at 04:44
  • Possible duplicate of [Flutter Countdown Timer](https://stackoverflow.com/questions/54610121/flutter-countdown-timer) – Yann39 Apr 10 '19 at 19:05
  • There is a timer app with flutter, you can check it out: https://github.com/pedromassango/xtimer-flutter-app – Pedro Massango Apr 10 '19 at 21:14
  • @flix how to use that class? i tried to write it but it say undefined class, i don't know what package it belong to. can you please show me how to use it? – ler Apr 10 '19 at 22:21

0 Answers0