问题
I am building a flutter auction application, I am stuck at the countdown time of an auction product so I use firebase realtime database. I have to make sure all users see the countdown at the same time. Please help me whether it's just a keyword to search for, a similar example or something that can help me. And I can use nodejs to assist,
This is my database, I want when a user posts a product of theirs, the time countdown, and I get that data to display it on the screen. Where do I put that countdown timer? In flutter or firebase. I'm crying. Thank you for everything,
回答1:
One simple solution is to set the ending DateTime
of your auction. For example, if you want your auction to be terminated after two hours, you can add
endingTime = DateTime.now().add(Duration(hours: 2))
to Firebase realtime database, and then when users come to your auction, you can just use a Timer.periodic
to calculate the remaining time for every 1 second, and stop the timer when the current DateTime
exceeds the termination time:
Timer.periodic(Duration(seconds: 1), (timer) {
remainingTime = endingTime.difference(DateTime.now());
if (remainingTime <= Duration.zero) {
timer.cancel()
}
});
And finally, you can just use setState
to render remainingTime
, or implement StreamController
with StreamBuilder
to render it. Hope it helps.
来源:https://stackoverflow.com/questions/62004082/how-to-display-the-countdown-time-for-all-users