I'm trying to create a countdown timer in Flutter that prints the remaining time every 5 seconds until the timer runs out, and then runs the same countdown timer for the next value in a list of values.
The following recursive function gets close, but it waits the "iteration" before going to the next value in the List
even when there is less time remaining for that Timer
.
import 'dart:async';
Future main() async {
final _sequence = [21, 10, 8];
final _iteration = 5;
void _countdown(seq) async {
if (seq.length > 0) {
var duration = seq[0];
print('Starting at $duration');
Timer.periodic(Duration(seconds: _iteration), (timer) {
var remaining = duration - timer.tick * _iteration;
if (remaining >= 0) {
print('$duration, $remaining');
} else {
timer.cancel();
_countdown(seq.sublist(1));
}
});
}
}
_countdown(_sequence);
}
Each time it runs the duration is defined by the value in the _sequence
List.
Even using the CountdownTimer
(instead of Timer.periodic
) has the same problem with waiting too long when the value remaining is less than the iteration:
import 'package:quiver/async.dart';
main() {
final _sequence = [21, 10, 8];
final _iteration = 5;
void _countdown(seq) {
if (seq.length > 0) {
var duration = seq[0];
print('Starting at $duration');
CountdownTimer countdownTimer = CountdownTimer(
Duration(seconds: duration),
Duration(seconds: _iteration),
);
var sub = countdownTimer.listen(null);
sub.onData((timer) {
if (timer.remaining > Duration(seconds: 0)) {
print('$duration, ${timer.remaining.inSeconds}');
} else {
sub.cancel();
_countdown(seq.sublist(1));
}
});
}
}
_countdown(_sequence);
}
The results should look like this with a 5 second pause between lines except where noted:
Starting at 21
21, 16
21, 11
21, 6
21, 1 <-- This one should only pause 1 second before continuing
Starting at 10
10, 5
10, 0 <-- This one should immediately continue
Starting at 8
8, 3 <-- This one should only pause 3 seconds before continuing