Flutter: Get Firebase Database reference child all data

Viewed 20706

I have a firebase database child which content is like below:

enter image description here

How to retrieve this in flutter?

My Current code:

static Future<Query> queryUsers() async{
return FirebaseDatabase.instance
    .reference()
    .child("zoom_users")
    .orderByChild('name');
}

queryUsers().then((query){
  query.once().then((snapshot){
    //Now how to retrive this snapshot? It's value data giving a json
  });
});
2 Answers

To retrieve the data try the following:

db = FirebaseDatabase.instance.reference().child("zoom_users");
db.once().then((DataSnapshot snapshot){
  Map<dynamic, dynamic> values = snapshot.value;
     values.forEach((key,values) {
      print(values["name"]);
    });
 });

Here first you add the reference at child zoom_users, then since value returns data['value'] you are able to assign it to Map<dynamic, dynamic> and then you loop inside the map using forEach and retrieve the values, example name.

Check this:

https://api.dartlang.org/stable/2.0.0/dart-core/Map/operator_get.html

Flutter: The method forEach isn't defined for the class DataSnapshot

  query.once().then((snapshot){
    var result = data.value.values as Iterable;
    for(var item in result) {
      print(item);
    }
  });

or with async that you already use

  var snapshot = await query.once();
  var result = snapshot.value.values as Iterable;
  for(var item in result) {
    print(item);
  }
Related