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

Jér*_*our 5 firebase firebase-realtime-database flutter

我尝试使用 Flutter 体验 Firebase Live 数据库。我只想在 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= '';
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

亲切的问候,杰罗姆

Ren*_*nec 4

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

我不知道在 Flutter/Dart 中您应该如何在快照的子级上循环,但您应该执行如下操作(在 JavaScript 中):

  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...
  });
Run Code Online (Sandbox Code Playgroud)

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

var user = new User.fromSnapShot(childSnapshot.key, childSnapshot.value);
Run Code Online (Sandbox Code Playgroud)