Home > Net >  Flutter Firebase Realtime Database get the Object Key in Query
Flutter Firebase Realtime Database get the Object Key in Query

Time:05-17

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

CodePudding user response:

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)
    }); 
  }
});

CodePudding user response:

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().

  • Related