Getting JSON Key Value from Firebase Datasnapshot

5,270

Solution 1

for accessing the key from DataSnapshot just use snapshot.key and you will have the relative key of the item in your case Users

 .then((onValue) {
   onValue.map(data => {
      var key = data.key
    })
 });

or just use as given in firebase docs inside then

.then(function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var key = childSnapshot.key; // you will get your key here
  });
});

Solution 2

You can get the key by snapshot.key, you can find a reference to it here:

snapshot.forEach(function(childSnapshot) {
  var childKey = childSnapshot.key;
  var childData = childSnapshot.val();
  // ...
});

https://firebase.google.com/docs/database/web/lists-of-data#listen_for_value_events

Share:
5,270
Wonderjimmy
Author by

Wonderjimmy

Updated on December 04, 2022

Comments

  • Wonderjimmy
    Wonderjimmy over 1 year

    Meanwhile I am developing a Flutter app with Firebase and it is enjoyable indeed, of course there is hassle to overcome...

    I setup a Firebase datastore, and through the firebase_database plugin I got a DataSnapshot returned as follow:

    enter image description here

    FirebaseDatabase.instance.reference().child('users')
      .orderByChild('emailAddress')
      .equalTo('[email protected]').once()
      .then((onValue) {
       Map data = onValue.value;
      });
    

    I use a Map object to keep this JSON. A stupid question: if I just want to get the value "-L474-TYYYGPvCChlZCS", how should I do?