Tayo.dev
Tayo.dev

Reputation: 1656

Flutter: Get Document Snapshot

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;
  }

Upvotes: 1

Views: 29976

Answers (3)

SOAMad
SOAMad

Reputation: 335

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.

Upvotes: 7

Nomi
Nomi

Reputation: 760

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;

}

Upvotes: 0

Mahmoud Mabrouk
Mahmoud Mabrouk

Reputation: 733

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

Upvotes: 0

Related Questions