简体   繁体   English

如何使用 flutter 流从 Firestore 获取数据

[英]How to get data from firestore using flutter streams

StreamBuilder<QuerySnapshot>(
              stream: _fireStore.collection('messages').orderBy('creation',descending: 
                                                                              true).snapshots(),
              // ignore: missing_return
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(
                      backgroundColor: Colors.lightBlueAccent,
                    ),
                  );
                }
//                print('i have data');
                print(snapshot.data.documents);

print(snapshot.data.documents);打印(快照.data.documents); is printing null value.正在打印 null 值。 'creation' is a timestamp field added into the fire store. 'creation' 是添加到火存储中的时间戳字段。

这是我的数据库的图像

https://github.com/umakanth-pendyala/Chat-app-with-flutter-and-fire-base is the link to my project in Github. https://github.com/umakanth-pendyala/Chat-app-with-flutter-and-fire-base是我在 Github 中的项目的链接。 And the code snippet is from the chat_screen page in the lib folder代码片段来自 lib 文件夹中的 chat_screen 页面

Try the following:尝试以下操作:

              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(
                      backgroundColor: Colors.lightBlueAccent,
                    ),
                  );
                }
               else if(snapshot.hasData){             
             print(snapshot.data.documents);
           } 
  return CircularProgressIndicator();

First you need to return a widget, next if you want to print the data then you need to check if the snapshot has data or no.首先你需要返回一个小部件,接下来如果你想打印数据那么你需要检查快照是否有数据。 In your code it will always print null since this is asynchronous.在您的代码中,它将始终打印 null 因为这是异步的。


After doing the above, also change the query to the following:完成上述操作后,还将查询更改为以下内容:

_fireStore.collection('messages').orderBy('created',descending: true).snapshots(),

Since you have a field called created in the document and not creation .由于您在文档中有一个名为created而不是creation的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM