如何使用StreamBuilder获取特定的Firestore文档

时间:2019-10-20 13:35:01

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

这是我当前正在使用的设置:

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)

1 个答案:

答案 0 :(得分:0)

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

类似这样:

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