关于firebase:Flutter:未为DataSnapshot类定义forEach方法

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

我需要迭代Firebase中DatabaseReference中的一个节点。 但是可以确定的是,firebase_database库中的DataSnapshot中没有forEach函数!

我还尝试使用firebase库中的DataSnapshot对象(其中具有forEach函数),但出现错误:

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

这是我的代码:

1
2
3
4
5
6
7
8
9
10
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;
  });
}


目前尚不清楚您要在代码中做什么,child(String path)val()在类DataSnapshot中都不存在,您可以在此处检查:

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

您也不能像这样循环:

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

因为您将收到以下错误:

enter image description here

这也意味着您不能在快照上使用forEach()进行迭代。

假设您有此数据库,并且想要获取names

1
2
3
4
5
user
  randomId
     name: John
  randomId
     name: Peter

您需要执行以下操作:

1
2
3
4
5
6
7
8
9
_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"]);
     });
 });

这里的参考指向节点users,因为snapshot.value的类型为Map,所以您可以执行此Map values=snapshot.value;

然后使用forEach()map中循环以获取键和值,您将获得以下输出:

output

这行I/flutter ( 2799): {-LItvfNi19tptjdCbHc3: {name: peter}, -LItvfNi19tptjdCbHc1: {name: john}}print(values.toString());的输出

以下两行:

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

print(k);的输出

其他两行是print(v["name"]);的输出

要将names添加到列表中,请在forEach()内执行以下操作:

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