I'm kind of new to the flutter programming so I'm trying to create some basic things to learn. Currently, I'm trying to create a list of countdowns to a specific date. Nothing fancy, the dates are retrieved through firestore and then shown in a list. However, I encountered a small issue:
All the dates start at the same hour, for now, this is 00:00:00, which means they should have the same seconds in the countdown at all times. This was not the case. I posted this question earlier this week and the issue was that I always used a new value for DateTime.now() so I 'solved' that part by creating a new variable in the main widget and passing it to the countdown. I used milliseconds and microseconds in this example because everything loads faster. But as you can see, now the mill/micro/seconds are nicely aligned (image from mobile), but it's not counting down anymore. So I'm reposting but now with a verifiable example in dartpad which can be found here. This code should be usable as well to replicate the problem on your local machine.
If I reload the app, it updates because the currentTime gets a new value of course.
Is anybody that could help me in the right direction?
CodePudding user response:
Once you are passing the currentTime
it stays the same. Because the currentTime
is initialized only once.
DateTime currentTime = DateTime.now();
And used
CountdownWidget(
startDate: DateTime(2023, 1), currentTime: currentTime),
The currentTime
value never get changes including the CountdownWidget
widget. Therefore the UI doesnt update.
You can change the value of CountdownWidget
from parent widget and pass the instance CountdownWidget
, the current way.
Solution 1: The solution will be
class _MyHomePageState extends State<MyHomePage> {
DateTime currentTime = DateTime.now();
@override
void initState() {
super.initState();
Timer.periodic(Duration(seconds: 1), (timer) {
currentTime = DateTime.now();
setState(() {});
});
}
It is changing the currentTime
on every second and passing the value, then updating the parent widget.
Solution 0:
Another solution will be handling the update on CountdownWidget
class CountdownWidgetState extends State<CountdownWidget> {
Timer? timer;
late DateTime currentTime = widget.currentTime;
@override
void initState() {
super.initState();
timer = Timer.periodic(const Duration(microseconds: 1), (timer) {
currentTime = DateTime.now();
setState(() {});
});
}