从Firebase Datasnapshot获取JSON密钥值

时间:2018-01-31 07:29:47

标签: json firebase firebase-realtime-database dart flutter

与此同时,我正在使用Firebase开发Flutter应用程序,确实非常有趣,当然有麻烦可以克服......

我设置了一个Firebase数据存储区,并通过firebase_database插件获得了一个DataSnapshot返回如下:

enter image description here

FirebaseDatabase.instance.reference().child('users')
  .orderByChild('emailAddress')
  .equalTo('wonderjimmy@gmail.com').once()
  .then((onValue) {
   Map data = onValue.value;
  });

我使用Map对象来保存这个JSON。一个愚蠢的问题:如果我只想获得值“ -L474-TYYYGPvCChlZCS ”,我该怎么办?

3 个答案:

答案 0 :(得分:4)

从DataSnapshot访问密钥只需使用snapshot.key,您将获得案例中项目的相对密钥用户

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

或者只是使用当时的firebase文档中给出的

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

答案 1 :(得分:1)

您可以通过snapshot.key获取密钥,您可以在此处找到对它的引用:

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

答案 2 :(得分:0)

这对我有用:

.then(res => {
      // console.log(res)
      const data = res.data
      // extracting firebase ids for manipulating existing notes
      for (let key in data) {
        const item = data[key]
        item.id = key
        console.log(item.id)
      }
相关问题