Umakanth Pendyala
Umakanth Pendyala

Reputation: 335

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); is printing null value. 'creation' is a timestamp field added into the fire store.

this is the image of my data base

https://github.com/umakanth-pendyala/Chat-app-with-flutter-and-fire-base is the link to my project in Github. And the code snippet is from the chat_screen page in the lib folder

Upvotes: 1

Views: 4698

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80934

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.


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.

Upvotes: 3

Related Questions