Flutter Firebase Realtime Database get the Object Key in Query

828

Solution 1

You need to loop inside the snapshot, for example:

FirebaseDatabase.instance.ref('usersnode/users').orderByChild('userId').equalTo("u1").get().then((snapshot) {
 if (snapshot.exists) {
   Map<dynamic, dynamic> values = snapshot.value;
    values.forEach((key, value) {
      print(key);
   }); 
  } else {
    print('No data available.1');
 }
});

After looping, you should be able to access both 0 and 1 by using the key property inside the forEach().

Solution 2

You can try:

List<String> _listKeys = [];
FirebaseDatabase.instance.ref('shop/products').get().then((snapshot) {
 if (snapshot.exists) {
  Map<dynamic, dynamic> values = snapshot.value;
      values.forEach((key, value) {
      _listKeys.add(key)
    }); 
  }
});
Share:
828
Tech Nerd
Author by

Tech Nerd

Updated on January 04, 2023

Comments

  • Tech Nerd
    Tech Nerd over 1 year

    I am new to FLutter and learning it to my own. I want to get the object key using the query from Firebase Realtime Database as highlighted in below screen shot: enter image description here

    My Query Method is:

    void queryDB(BuildContext context) async {
        AppUtil.showLoader(context: context);
        String userId = "u1";
        FirebaseDatabase.instance.ref('usersnode/users').orderByChild('userId').equalTo("u1").get().then((snapshot) {
          if (snapshot.exists) {
            print("KEY:::" + snapshot.key);
           
          } else {
            print('No data available.1');
          }
          AppUtil.dismissLoader(context: context);
         
        });
      }
    

    It always print users but my expectation is to get 0

    Thanks in Advance