【问题标题】:How to get a specific Firestore document with a StreamBuilder如何使用 StreamBuilder 获取特定的 Firestore 文档
【发布时间】:2020-02-16 18:57:37
【问题描述】:

这是我目前使用的设置:

class BookList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('books').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError)
          return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting: return new Text('Loading...');
          default:
            return new ListView(
              children: snapshot.data.documents.map((DocumentSnapshot document) {
                return new ListTile(
                  title: new Text(document['title']),
                  subtitle: new Text(document['author']),
                );
              }).toList(),
            );
        }
      },
    );
  }
}

当我想得到一个特定的文档时,我看到了这个例子:

Firestore.instance
        .collection('talks')
        .document('document-name')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot
    });

问题是我不知道如何在我的 Streambuilder 中使用该示例。当我尝试这个时:

...

body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance
        .collection('talks')
        .document('document-name')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot
    }),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.data == null)
            return Center(child: CircularProgressIndicator());
          if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
          if (snapshot.data.documents.length == 0)
...

我明白了:

参数类型'Future'不能分配给参数类型'Stream'.dart(argument_type_not_assignable)

【问题讨论】:

    标签: firebase firebase-realtime-database flutter google-cloud-firestore


    【解决方案1】:

    在 Firestore 的 Flutter 库中,您可以通过调用 DocumentReference.snapshots() method 来获取单个文档的流。

    比如:

    stream: Firestore.instance.collection('books').document('document-name').snapshots(),
    

    【讨论】:

    • 谢谢,我得到了它与您的参考资料一起使用并将我的 QuerySnapshot 更改为 DocumentSnapshot
    猜你喜欢
    • 2020-03-04
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-10-22
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多