Flutter: Get Document Snapshot

flutter firestore get document
flutter firestore get document field
flutter firestore get all document
flutter firestore transaction
flutter firestore add document
flutter firestore check if document exists
firebase get document
firestore get document by id

I created a Listview builder passing buildChatList as my itembuilder but i noticed nothing is returned from the buildChatList when i HOT RESTART or Rebuild the app BUT actually returned the expected Data when i HOT RELOAD. I don't understand why this is happening. I need help.

Below is my code so far.

buildChatList(BuildContext context, int index) {
    Map<String, dynamic> userDocumentt;
    print('INDEX $index COUNT $currentUserActiveChatsLength');
    String thisUserID = currentUserActiveChats[index];
    if (user.uid.hashCode <= thisUserID.hashCode) {
      groupChatId = '$_cuserID-$thisUserID';
    } else {
      groupChatId = '$thisUserID-$_cuserID';
    }
    Stream<QuerySnapshot> unreadMessages = Firestore.instance
        .collection('messages')
        .where("chatDetails.to", isEqualTo: user.uid)
        .where("chatDetails.sender", isEqualTo: thisUserID)
        .where("chatDetails.hasRead", isEqualTo: false)
        .snapshots();
    unreadMessages.listen((QuerySnapshot data) {
      unReadMessageLength = data.documents.length;
    });

    Stream<QuerySnapshot> lastMess = Firestore.instance
        .collection('messages')
        .where('groupChatId', isEqualTo: groupChatId)
        .orderBy('chatDetails.timestamp', descending: true)
        .limit(1)
        .snapshots();
    lastMess.listen((QuerySnapshot data) {
      List<DocumentSnapshot> userLastMess = data.documents;
      chatDetailSnapshotList = userLastMess.map((DocumentSnapshot doc) {
        return doc.data;
      }).toList();
    });
    Stream<DocumentSnapshot> userP = usersRef.document(thisUserID).snapshots();
    userP.listen((DocumentSnapshot snap) {
      userDocumentt = Map.from(snap.data);
      if (userDocumentt != null) {
        print('HELLOo $userDocumentt');
        myResult = new InkWell(
          highlightColor: Colors.grey[300],
          onTap: () {
            Navigator.of(context, rootNavigator: true).push(
                new MaterialPageRoute(
                    builder: (context) =>
                        new Chat(chatWith: userDocumentt['id'])));
          },
          onLongPress: () {
            setState(() {
              modifyMode = true;
            });
          },
          child: new Container(
            margin: EdgeInsets.only(left: 15.0, right: 15.0),
            child: new Column(
              children: <Widget>[
                new Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[

                    new Expanded(
                      child: new Container(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 5.0),
                              child: new Text(
                                userDocumentt['username'],
                                style: new TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                            ),
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 7.0),
                              child: new Text(
                                chatDetailSnapshotList[0]["chatDetails"]
                                    ["content"],
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: new TextStyle(
                                  fontSize: 15.0,
                                  color: Colors.grey[800],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                new Container(
                  margin: EdgeInsets.only(left: 72.0, top: 6.0, bottom: 6.0),
                  child: new Divider(
                    color: Colors.grey[300],
                    height: 10.0,
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        print('HELLLLOOO $userDocumentt');
        myResult = CircularProgressIndicator();
      }
    });
    return myResult;
  }

For Firestore It make sense to use 'StreamBuilder' for real time updates, I am giving you a sample code I have for the same, Hope it helps.

StreamBuilder(
                 stream: Firestore.instance.collection("YourCollectionNAme").snapshots(),
                 builder: (BuildContext  context,AsyncSnapshot snapshot)
                 {
                   if (snapshot.hasData)
                   {
                   return new ListView.builder(
                     shrinkWrap: true,
                     itemCount: snapshot.data.documents.length,
                     padding: const EdgeInsets.only(top: 5.0),
                     itemBuilder: (context, index) {
                      DocumentSnapshot ds = snapshot.data.documents[index];
                      return new Row(
                        textDirection: TextDirection.ltr,
                          children: <Widget>[
                            Expanded (child:Text(ds["Field-of-collection"]) ),
                            Expanded (child:Text(ds["another-field"]) ),
                            Expanded (child:Text(ds["last-field"].toString()) ),


                          ],
                      );
      }
                   );
                 }
                 },
               )

I am using List view for my Firestore collection.

A DocumentSnapshot contains data read from a document in your Cloud Firestore database. The data can be extracted with data() or get(<field>) to get a  Looks like maybe because you got a stream builder, so the Snapshot is a AsyncSnapshot<dynamic>, when you grab its .data, you get a dynamic, which returns a DocumentSnapshot, which then you need to call .data on this object to get the proper Map<String, dynamic> data.

you will need to use StreamBuilder instead of normal ListView.builder(). check this link

Updating data does not mean updating the view you need to rebuild this widget on every new record added, so when you HOT RELOAD the app you run setState() manually so it shows the update.

StreamBuilder will do this setState() for you on every new record

Get a specific document: Firestore.instance .collection('talks') .document('​document-name') .get() .then((DocumentSnapshot ds) { // use ds as a snapshot });​. A DocumentSnapshot contains data read from a document in your Cloud Firestore database. The true if the document existed in this snapshot. public T get

I guess you are not returning stream try this.

buildChatList(BuildContext context, int index) {
Map<String, dynamic> userDocumentt;
print('INDEX $index COUNT $currentUserActiveChatsLength');
String thisUserID = currentUserActiveChats[index];
if (user.uid.hashCode <= thisUserID.hashCode) {
  groupChatId = '$_cuserID-$thisUserID';
} else {
  groupChatId = '$thisUserID-$_cuserID';
}
Stream<QuerySnapshot> unreadMessages = Firestore.instance
    .collection('messages')
    .where("chatDetails.to", isEqualTo: user.uid)
    .where("chatDetails.sender", isEqualTo: thisUserID)
    .where("chatDetails.hasRead", isEqualTo: false)
    .snapshots();
unreadMessages.listen((QuerySnapshot data) {
  unReadMessageLength = data.documents.length;
});

Stream<QuerySnapshot> lastMess = Firestore.instance
    .collection('messages')
    .where('groupChatId', isEqualTo: groupChatId)
    .orderBy('chatDetails.timestamp', descending: true)
    .limit(1)
    .snapshots();
lastMess.listen((QuerySnapshot data) {
  List<DocumentSnapshot> userLastMess = data.documents;
  chatDetailSnapshotList = userLastMess.map((DocumentSnapshot doc) {
    return doc.data;
  }).toList();
});
myResult = Stream<DocumentSnapshot> userP = usersRef.document(thisUserID).snapshots();
userP.listen((DocumentSnapshot snap) {
  userDocumentt = Map.from(snap.data);
  if (userDocumentt != null) {
    print('HELLOo $userDocumentt');
    return InkWell(
      highlightColor: Colors.grey[300],
      onTap: () {
        Navigator.of(context, rootNavigator: true).push(
            new MaterialPageRoute(
                builder: (context) =>
                    new Chat(chatWith: userDocumentt['id'])));
      },
      onLongPress: () {
        setState(() {
          modifyMode = true;
        });
      },
      child: new Container(
        margin: EdgeInsets.only(left: 15.0, right: 15.0),
        child: new Column(
          children: <Widget>[
            new Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: new Container(
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        new Container(
                          margin: EdgeInsets.only(left: 17.0, top: 5.0),
                          child: new Text(
                            userDocumentt['username'],
                            style: new TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16.0,
                            ),
                          ),
                        ),
                        new Container(
                          margin: EdgeInsets.only(left: 17.0, top: 7.0),
                          child: new Text(
                            chatDetailSnapshotList[0]["chatDetails"]
                                ["content"],
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: new TextStyle(
                              fontSize: 15.0,
                              color: Colors.grey[800],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            new Container(
              margin: EdgeInsets.only(left: 72.0, top: 6.0, bottom: 6.0),
              child: new Divider(
                color: Colors.grey[300],
                height: 10.0,
              ),
            ),
          ],
        ),
      ),
    );
  } else {

    //
    print('HELLLLOOO $userDocumentt');
    myResult = CircularProgressIndicator();
  }
});
return myResult;

}

Contents Setup Usage Getting Started Issues and feedback .document('​document-name') .get() .then((DocumentSnapshot ds) { // use ds as a snapshot });​. A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. A DocumentSnapshot contains data read from a document in your Cloud Firestore database. The data can be extracted with the getData () or get (String) methods. If the DocumentSnapshot points to a non-existing document, getData () and

Getting data. Get a single document. Future<DocumentSnapshot> car = database.collection('cars') .document('  Also, you'd probably get quicker responses about this type of thing (i.e. not an actual bug with flutter but rather a problem you're having) from stackoverflow, the realtime chat channel, or the google group mailing list.

I am trying to map a DocumentSnap from Firebase to a Json Class in Flutter. I can confirm that my is getting the data from the document, but i  itemCount: snapshot.data.documents.length, We are returning a Text if the data is under the fetching process and if the data is loaded from the database then we build a ListView.builder which

A collection can have any number of Documents, these Documents contains data​. flutter packages get Retrieve and Display Snapshot. When querying a collection you can get zero, one or more documents as a result, by going through the following steps. Create a CollectionReference that points to the collection you want documents

Comments
  • Are you fetching data (using streams) within a build() method? That would not work. You should setup all your listeners in the initState() method, and whenever they fire, use setState() to update the internal component state and then rebuild the UI.
  • that works really well but what happens when I have to get a document based on a uid that I don't have ready yet? I need to load the documents of the user is using the app so the authentication takes a bit until I can get this uids
  • did you try to use auth or login page before anything in the app?
  • no but because I don't need it. The user will log in... or not. If he doesn't want to, I need to wait until he logs in first to get his uid
  • in that case, use conditions like if uid present, load x stuff