I’m trying to get data from realtime database in firebase but all I could reach is having it in the below format:
I/flutter (12286): {OotKWLn1QoYfF9NFx78gRwwnnli1: {isHost: false, isJudge: false, name: Maurice Azmy, id: OotKWLn1QoYfF9NFx78gRwwnnli1, isLoaded: false}}
I want to access name only for example so I can save "Maurice Azmy" as a string in variable.
My code looks like the below:
DatabaseReference playersRef = FirebaseDatabase.instance.ref().child("rooms/$roomCode/players");
playersRef.onValue.listen((DatabaseEvent event) {
print("====");
print(event.snapshot.value);
print("====");
});
I tried using event.snapshot.value[‘name’] but in vain.
I want to access each value in the database separately.
2
Answers
Let’s examine this:
I/flutter (12286): {OotKWLn1QoYfF9NFx78gRwwnnli1: {isHost: false, isJudge: false, name: Maurice Azmy, id: OotKWLn1QoYfF9NFx78gRwwnnli1, isLoaded: false}}
Let’s remove everything that isn’t the actual data returned by Firebase.
{OotKWLn1QoYfF9NFx78gRwwnnli1: {isHost: false, isJudge: false, name: Maurice Azmy, id: OotKWLn1QoYfF9NFx78gRwwnnli1, isLoaded: false}}
Let’s parse that into an actual map, because that’s what Firebase uses.
If you print the type of the
eventSnapshotValue
variable, you will see_Map<String, Map<String, Object>>
. The problem is that you have a nested map, and your key is not in that outer map… it is in the inner map.There is the outer map:
This is the inner map:
Since you’re probably not going to store the
id
properties, you can just iterate through the values of your outer map. Every single value of your outer map is another map which contains the data you’re looking for.To access, simply do this:
It looks like your
rooms/$roomCode/players
contains a list of children. Even if there’s only one chat, the snapshot you get back still will be a list of that one child. You can loop oversnapshot.children
to get the individual child node(s).So something like: