Home > Net >  Accessing the last child of a child in firebase real time database
Accessing the last child of a child in firebase real time database

Time:09-24

I want to access the last child within a certain child in real time database enter image description here

(this child)

I tried using this code but it returns {-MkHrcId8EfYpqFWqNrw: {Sender: 97205********, message: hello}} when accessing snapshot.value, but returns null when when trying to access snapshot.value['message']

  Future<String> getLastMessage() async{
    final ref = FirebaseDatabase.instance.reference();
    String RoomId; // RoomId is the name of the first child, the one that starts with 587 in the image
    String lastMessage;
    lastMessage = await ref.child(RoomId).orderByKey().limitToLast(1).once().then((snapshot) {
      snapshot.value['message'];
    return lastMessage;
    });

CodePudding user response:

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So your callback will need to handle that list, by looping over its children (in snapshot.value.values iirc), or by accessing the first entry directly with snapshot.value.toList()[0]['message'].

CodePudding user response:

based on @Frank van Puffelen answer the solution ended up being this

lastMessage = await ref.child(RommId).orderByKey().limitToLast(1).once().then((snapshot) {
       return (snapshot.value.values).toList()[0]['message'];
    });
  • Related