frlzjosh
frlzjosh

Reputation: 462

Unable to listen to incoming data from Realtime Database (RTDB) in flutter

Here is the structure of my realtime database.

enter image description here

In Flutter (ios) I try creating a reference with the code below:

final tempRef = FirebaseDatabase.instance.reference().child("temp_hum");

Then I follow the common protocol to listen for changes in the database with the code below and I can't event get the print statement in _onIncomingEvent to work

class _TemperatureProgressState extends State<TemperatureProgress> {
  List<Temperature> tempList;
  StreamSubscription<Event> _onTempSubscription;

 _onIncomingTemp(Event event) {
    print('event: ' +  event.snapshot.toString());
 }
   @override
  void initState() {
    super.initState();
    tempList = new List();
    _onTempSubscription = tempRef.onChildAdded.listen(_onIncomingTemp);
    print('sup');
  }
}

Any ideas? I am thinking one of the following is the error: - that my code might be wrong - I am not creating my firebase reference properly with child('temp_hum') - I might not even be connected to the right database?

UPDATE 1: - I found out that I was pointing to the wrong database URL in my GoogleService-Info.splist file. Still unable to get incoming data though

UPDATE 2: - I'm now able to get data by listening from .then(). However, I only get the data once, is there a way to keep on listening?

tempRef.once().then((DataSnapshot snapshot){
   print('data: ${snapshot.value}');
});

Upvotes: 2

Views: 2071

Answers (1)

frlzjosh
frlzjosh

Reputation: 462

Found the solution, code will be below. As Frank in the comment says, once() will only make a query once, so it will work for retrieving data from a get request. My requirement was to continuously listen to data. Just an extra piece of info, limitToLast(1) will receive the most recent piece of data instead of receiving everything from whatever collection you're "listening" to from Firebase's Realtime Database.


    tempRef.limitToLast(1).onValue.listen((Event event) {
       Map data = event.snapshot.value;
          data.forEach((index, data) => {
             print('weight data: ${data}'),
             setState((){
               weightList.add(new Weight(data['avg_weight'], data['hive_weight'], data['object_id'], data['time'], data['user_id']));
          })
       });
    });

Upvotes: 1

Related Questions