【问题标题】:How to get data from firestore using flutter streams如何使用颤振流从 Firestore 获取数据
【发布时间】:2020-06-14 13:16:35
【问题描述】:
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);

打印(snapshot.data.documents);正在打印空值。 'creation' 是添加到火存储中的时间戳字段。

https://github.com/umakanth-pendyala/Chat-app-with-flutter-and-fire-base 是我在 Github 中的项目的链接。而代码sn -p来自lib文件夹中的chat_screen页面

【问题讨论】:

  • 您似乎也在 Udemy 参加 Angela 的培训课程。相同的屏幕名称。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

尝试以下方法:

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

首先你需要返回一个小部件,接下来如果你想打印数据那么你需要检查快照是否有数据。在您的代码中,它将始终打印 null 因为这是异步的。


做完上面的,也把查询改成如下:

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

因为您在文档中有一个名为 created 而不是 creation 的字段。

【讨论】:

  • 我已经完成了你要求我做的事情,但我似乎没有得到任何数据,我猜这个流有问题:_fireStore.collection('messages') .orderBy('creation',descending: true).snapshots()',
  • 添加你的数据库截图
  • 我已经添加了截图。如果我将流: _fireStore.collection('messages').orderBy('creation',descending: true).snapshots(), 替换为 _fireStore.collection('messages').snapshots() 那么它可以工作,但消息不是有条不紊地进行
  • 天啊。这是一个愚蠢的错误。我会立即将答案标记为正确。并感谢您的帮助
  • 很抱歉问你这个问题。但是您建议的解决方案效果很好。但即使我添加了 orderBy 方法,我还是以无序的方式看到了我的聊天消息。你能帮我解决这个问题吗??
猜你喜欢
  • 2021-12-22
  • 2021-03-04
  • 2021-10-01
  • 2021-08-18
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
相关资源
最近更新 更多