Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my Firebase Realtime Database data showing up out of order when I use a listener?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When you get a list of data from Firebase Realtime Database, the DataSnapshot has three pieces of information for the child nodes:

  1. Their keys
  2. Their values
  3. 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) {
    ...
  }
  ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading