I am using an onValue listener to listen to a node in my Firebase Realtime Database. I should be getting chat messages in the order that they were written to the database, but for some reason I’m getting the 4th, 1st, 3rd, then the 2nd message. Why is this?
void getChatListener() async {
final node = 'chats';
_groupChatRef = FirebaseDatabase.instance.ref(node);
_chatsSubscription = _groupChatRef.onValue.listen((DatabaseEvent event) {
if (event.snapshot.value != null) {
dataList = [];
final data = event.snapshot.value as Map<dynamic, dynamic>;
data.forEach((key, value) {
dataList.add(value);
});
setState(() {
chats = dataList;
});
}
});
}
//later on the widget builds a ListView using the chats variable
>Solution :
When you get a list of data from Firebase Realtime Database, the DataSnapshot has three pieces of information for the child nodes:
- Their keys
- Their values
- Their relative order to each other
When you call value on a snapshot, the information is converted into a map – which only has space for the keys and values. So the information about the order is lost at this point.
To maintain the order, process the child nodes as shown in the documentation on listening for a list with onValue:
_chatsSubscription = _groupChatRef.onValue.listen((DatabaseEvent event) {
for (final child in event.snapshot.children) {
...
}
...