Flutter Firebase RTDB onValue triggered multiple times

Issue

I’m developing an app which needs live data from the database which was created using Firebase RTDB. I used onValue to get the live data, the problem is that the onValue is triggered multiple times when a lot of data changed at once and messed up my data processing system. Been trying to look for solutions, but still haven’t managed to find one. Any help will be appreciated. Here’s the code:

await refConnection
        .child(user!.uid).orderByChild('date_created').onValue.forEach((element) {
          if (element.snapshot.value != null) {
            Map<dynamic, dynamic> connection = element.snapshot.value as Map<
                dynamic,
                dynamic>;
            print("Test: $connection");
            

            connection.forEach((key, value) {
              if (connection[key]['status'] == 'connected') {
                Provider.of<ContactDataProvider>(context, listen: false)
                    .addConnected(connection[key]);
              } else if (connection[key]['status'] == 'incoming_req') {
                Provider.of<ContactDataProvider>(context, listen: false)
                    .addIncoming(connection[key]);
              } else if (connection[key]['status'] == 'sent_req') {
                print(connection[key]);
                Provider.of<ContactDataProvider>(context, listen: false)
                    .addSent(connection[key]);
              }
            });

            setState();
          }
    });

Solution

As jjkbm has suggested, I decided to try a different approach by removing the foreach. It works fine after that.

Answered By – treble18

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *