'Flutter Firebase Realtime Database get the Object Key in Query
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:

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
Solution 1:[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:[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)
});
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Haddad |
| Solution 2 | Saitoh Akira |
