且构网

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

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

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

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

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.