Flutter: The method forEach isn't defined for

2019-02-26 03:41发布

问题:

I need to iterate a node in a DatabaseReference in firebase. But it is wired that there is no forEach function in DataSnapshot that is in firebase_database library!

I also tried to use DataSnapshot object that is in firebase library (that has a forEach function in it) but I got a error:

[dart] The argument type '(DataSnapshot) → List<dynamic>' can't be assigned to the parameter type '(DataSnapshot) → FutureOr<dynamic>'.

And here is my code:

getAccountsList() {
  return firebaseDbService.getAccounts().once().then((DataSnapshot snapshot) {
    var list = [];
    snapshot.forEach((DataSnapshot account) => list.add({
      'id': snapshot.key,
      'name': snapshot.child('name').val(),
    }));
    return list;
  });
}

回答1:

It's unclear what you are trying to do in your code, both child(String path) and val() do not exist in the class DataSnapshot, you can check here:

https://github.com/flutter/plugins/blob/master/packages/firebase_database/lib/src/event.dart#L27

Also you cannot loop like this:

for( var values in snapshot.value){
 print("Connected to second database and read ${values}");
}

since you will get the following error:

which means also you cannot use forEach() on the snapshot to iterate.


Let's say you have this database, and you want to get the names:

user
  randomId
     name: John
  randomId
     name: Peter

You need to do the following:

_db=FirebaseDatabase.instance.reference().child("user");
_db.once().then((DataSnapshot snapshot){
   Map<dynamic, dynamic> values=snapshot.value;
   print(values.toString());
     values.forEach((k,v) {
        print(k);
        print(v["name"]);
     });
 });

Here the reference points toward the node users, since snapshot.value is of type Map<dynamic,dynamic> then you are able to do this Map<dynamic, dynamic> values=snapshot.value;.

Then you loop inside the map using forEach() to be able to get the keys and values, you will get the following output:

This line I/flutter ( 2799): {-LItvfNi19tptjdCbHc3: {name: peter}, -LItvfNi19tptjdCbHc1: {name: john}} is the output of print(values.toString());

Both the following lines:

I/flutter ( 2799): -LItvfNi19tptjdCbHc3
I/flutter ( 2799): -LItvfNi19tptjdCbHc1

are the output of print(k);

The other two lines are the output of print(v["name"]);

To add the names into a list do the following inside the forEach():

list.add(v["name"]);
    print(list);