Pierre
Pierre

Reputation: 57

Flutter Read Realtime Database

I'm trying to count the number of messages in my Firebase Realtime Database but I can't read further than the first 'messages' branch.

I use this command to display the exact number of conversations I've created.

FirebaseDatabase.instance.reference().child('messages').once().then((DataSnapshot snapshot){
  print(snapshot.value.length);
});

He looks good to me 14 but I need to do a count of each message created in each branch (chat room).

To understand the tree structure:

messages ----------id chat room -------------id message

database

Upvotes: 0

Views: 1483

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599176

One way to do this is to use the onChildAdded stream. This stream is called with each child node of the location on which you listen, so one level lower in the JSON tree.

It would look something like:

FirebaseDatabase.instance.reference().child('messages').onChildAdded.listen((Event event) {
    print(event.snapshot.value.length);
});

When you first call onChildAdded.listen, the length for each existing child node will be printed. Then afterwards, if you add a new child node (directly) under messages, the length of that will be printed too.

Upvotes: 2

Related Questions