flutter/firebase数据库中的简单查询 [英] A simple Query in flutter/firebase database
问题描述
我尝试体验Flubase的Firebase Live数据库. 我只是想在firebase响应的datasnapshot中获取一个值.
I try to experience Firebase Live database with flutter. I just would like to get a value in the datasnapshot of the firebase response.
我的Firebase
My Firebase
我的代码
static Future<User> getUser(String userKey) async {
Completer<User> completer = new Completer<User>();
String accountKey = await Preferences.getAccountKey();
FirebaseDatabase.instance
.reference()
.child("accounts")
.child(accountKey)
.child("users")
.childOrderBy("Group_id")
.equals("54")
.once()
.then((DataSnapshot snapshot) {
var user = new User.fromSnapShot(snapshot.key, snapshot.value);
completer.complete(user);
});
return completer.future;
}
}
class User {
final String key;
String firstName;
Todo.fromJson(this.key, Map data) {
firstname= data['Firstname'];
if (firstname== null) {
firstname= '';
}
}
}
我的名字为Null. 我想我应该导航到snapshot.value的子级.但是无法通过foreach或Map()...来管理.
I got Null value for firstname. I guess I should navigate to the child of snapshot.value. But impossible to manage with foreach, or Map(), ...
亲切的问候,杰罗姆
推荐答案
You are querying with a query and the documentation for Queries (here in JavaScript, but it is valid for all languages), says that "even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result."
我不知道您应该如何在Flutter/Dart中循环遍历快照的子级,但是您应该执行以下操作(在JavaScript中):
I don't know exactly how you should loop, in Flutter/Dart, over the children of the snapshot but you should do something like the following (in JavaScript):
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
// ...
});
,并假设您的查询仅返回一条记录(一条匹配项"),则在执行操作时使用子快照
and assuming that your query returns only one record ("one single match"), use the child snapshot when you do
var user = new User.fromSnapShot(childSnapshot.key, childSnapshot.value);
这篇关于flutter/firebase数据库中的简单查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!