且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Flutter中的Firestore查询单个文档(cloud_firestore插件)

更新时间:2023-02-14 10:03:55


但这似乎不是正确的语法。

but that does not seem to be correct syntax.

语法不正确,因为您缺少 collection()调用。您不能直接在 Firestore.instance 上调用 document()。要解决此问题,您应该使用类似以下的方法:

It is not the correct syntax because you are missing a collection() call. You cannot call document() directly on your Firestore.instance. To solve this, you should use something like this:

var document = await Firestore.instance.collection('COLLECTION_NAME').document('TESTID1');
document.get() => then(function(document) {
    print(document("name"));
});

或更简单的方式:

var document = await Firestore.instance.document('COLLECTION_NAME/TESTID1');
document.get() => then(function(document) {
    print(document("name"));
});

如果要实时获取数据,请使用以下代码:

If you want to get data in realtime, please use the following code:

Widget build(BuildContext context) {
  return new StreamBuilder(
      stream: Firestore.instance.collection('COLLECTION_NAME').document('TESTID1').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return new Text("Loading");
        }
        var userDocument = snapshot.data;
        return new Text(userDocument["name"]);
      }
  );
}

这还将帮助您将名称设置为文本视图。

It will help you set also the name to a text view.