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.