Reputation: 4519
I am trying to calculate time left from the time a post was added into database. I want the multiple devices to see the same countdown timer.
round {
seconds: 5,
time: 1619971281887 (ServerValue.timstamp)
}
And using the following code to calculate time left. This code is an adaptation of code in How to implement a distributed countdown timer in Firebase
databaseReference.child(code).child("round").onValue.listen((event) {
var seconds = event.snapshot.value['seconds'];
var startAt = event.snapshot.value['time'];
Timer.periodic(new Duration(seconds: 1), (timer) {
var timeLeft = (seconds * 1000) -
((DateTime.now().millisecondsSinceEpoch -
startAt -
serverTimeOffset));
print("Seconds");
print(seconds * 1000);
print("Time Now");
print(DateTime.now().millisecondsSinceEpoch);
print("Start At");
print(startAt);
print("Offset");
print(serverTimeOffset);
print("Time Left");
print(timeLeft);
if (timeLeft < 0) {
timer.cancel();
} else {
var show = (timeLeft / 1000).floor();
var per = (timeLeft % 1000);
//print(show);
//print(per);
}
});
});
In order to see if the above code was working properly, I have added a couple of print calls. The issue is that startAt keeps on updating itself for some reason. And not sure why is that. Would appreciate if someone could shed some light.
Some of the output from console is as follows:
flutter: Start At
flutter: 1619982194189
flutter: Time Left
flutter: 10506.6201171875
flutter: Start At
flutter: 1619982193226
flutter: Time Left
flutter: 9315.6201171875
Upvotes: 0
Views: 506
Reputation: 599176
If your onValue
gets called multiple times, that means the value in the database is being updated. The code you shared doesn't how any such update happening, so I recommend searching the rest of your code for such writes.
You should also be able to see the updates by looking at the node in the Firebase console. This allows you to see exactly when the update happens, and might make it easier to find the sour.ce
Finally, if you don't care about updates, you can use once()
instead onValue to only get a value from the database once.
Upvotes: 1
Reputation: 26397
If code is running and you are not sure why it's running the best way to find out is to use the debugger and see when the code is called.
Given your code it's going to update whenever there's a new event and also start a new timer.
Upvotes: 0