Mah*_*deh 4 dart firebase firebase-realtime-database flutter
我需要DatabaseReference在 firebase 中迭代一个节点。但是连图书馆里没有那个forEach功能!DataSnapshotfirebase_database
我还尝试使用库中的DataSnapshot对象firebase(其中包含 forEach 函数),但出现错误:
[dart] The argument type '(DataSnapshot) ? List<dynamic>' can't be assigned to the parameter type '(DataSnapshot) ? FutureOr<dynamic>'.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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;
});
}
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚您要在代码中做什么,child(String path)并且val()在类中都不存在DataSnapshot,您可以在此处查看:
https://github.com/flutter/plugins/blob/master/packages/firebase_database/lib/src/event.dart#L27
你也不能像这样循环:
for( var values in snapshot.value){
print("Connected to second database and read ${values}");
}
Run Code Online (Sandbox Code Playgroud)
因为你会得到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
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"]);
});
});
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6743 次 |
| 最近记录: |