flutter / firebase数据库中的简单查询

问题描述 投票:2回答:2

我尝试使用flutter体验Firebase Live数据库。我只想获得firebase响应的数据快照中的值。

我的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= '';
    }
  }
}

我得到名字的空值。我想我应该导航到snapshot.value的孩子。但是无法用foreach或Map()来管理......

亲切的问候,杰罗姆

firebase firebase-realtime-database flutter
2个回答
2
投票

您正在查询查询和查询文档(here in JavaScript,但它对所有语言都有效),说“即使查询只有一个匹配项,快照仍然是一个列表;它只包含一个要访问该项目,您需要循环结果。“

我不知道你应该如何在Flutter / Dart中循环快照的子项,但你应该做类似以下的事情(在JavaScript中):

  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...
  });

并假设您的查询只返回一条记录(“一个匹配”),请在执行时使用子快照

var user = new User.fromSnapShot(childSnapshot.key, childSnapshot.value);

0
投票

这将为用户提供可重复使用的对话框。如果您不使用流和流构建器,可能会对您自己造成轻微的伤害,下面的解决方案是在FirebaseDB上一次性获取用户的集合。

class User {
  String firstName, groupID, lastName, pictureURL, userID;

  User({this.firstName, this.groupID, this.lastName, this.pictureURL, this.userID});
  factory User.fromJSON(Map<dynamic, dynamic> user) => User(firstName: user["Firstname"], groupID: user["Group_id"], lastName: user["Lastname"], pictureURL: user["Picturelink"], userID: user["User_id"]);
}

Future<List<User>> users = Firestore.instance.collection("users").snapshots().asyncMap((users) {
  return users.documents.map((user) => User.fromJSON(user.data)).toList();
}).single;
© www.soinside.com 2019 - 2024. All rights reserved.