问题
I'm trying to set timestamp into firebase realtime database but when I retrieve, not ordering by timestamp. I did like so.
FirebaseDatabase.instance.reference().child('path').push().set({
'timestamp': ServerValue.timestamp
});
This is the node
Then I retrieve like so.
FirebaseDatabase.instance.reference().child('path').orderByChild('timestamp').once().then((snap) {
print(snap.value);
});
but output is this
{-LJhyfmrWVDD2ZgJdfMR: {timestamp: 1534074731794}, -LJhyWVi6LddGwVye48K: {timestamp: 1534074689667}, -LJhzDlvEMunxBpRmTkI: {timestamp: 1534074875091}
Those are not ordered by timestamp. Am I missing something? Otherwise is this firebase error or flutter?
回答1:
The data is retrieved in the right order into a DataSnapshot. But when you call snap.value the information from the snapshot has to be converted into a Map<String, Object>, which not longer can hold information about the order of the child nodes.
To maintain the order, you have to process the child nodes from the DataSnapshot with a loop. I'm not an expert in Flutter (at all), but I can't quickly find a way to do this for a value event. So you might want to instead listen for .childAdded:
FirebaseDatabase.instance
.reference()
.child('path')
.orderByChild('timestamp')
.onChildAdded
.listen((Event event) {
print(event.snapshot.value);
})
来源:https://stackoverflow.com/questions/51808719/flutter-firebase-database-wrong-timestamp-order