Flutter: The method forEach isn't defined for the class DataSnapshot
我需要迭代Firebase中
我还尝试使用
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; }); } |
目前尚不清楚您要在代码中做什么,
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}"); } |
因为您将收到以下错误:
这也意味着您不能在快照上使用
假设您有此数据库,并且想要获取
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"]); }); }); |
这里的参考指向节点
然后使用
这行
以下两行:
1 2 | I/flutter ( 2799): -LItvfNi19tptjdCbHc3 I/flutter ( 2799): -LItvfNi19tptjdCbHc1 |
是
其他两行是
要将
1 2 | list.add(v["name"]); print(list); |