Flutter - How to use ScrollController to jumpto the bottom of the listview after fetching data from firebase using StreamBuilder?

1,200

Of course, the scrollcontroller is the first thing that comes to mind to make a chat go down to the last message sent. But it's not the only way to do it.

I provide a solution that I found when I was making a chat system:

StreamBuilder(
      stream: FirebaseFirestore.instance
      .collection('<MessagesColection>')
      .orderBy('<Time field>',descending: true)
      .snapshots(),
      builder: (context,snapshot) {                    
          return ListView.builder(
            //The reversed list will put the list backwards. 
            //The start of the list will start at the bottom.
            reverse: true, 
            controller: scrollController,      
            itemCount: snapshot.data.size,
            itemBuilder: (context, index) {                                                    
              return ChatMessage(snapshot);          
            },
          );
        }
    ),

In the previous code, what was done was to invert the list, the most recent messages will be at the bottom, and order the records in descending order, that is, from the most recent to the least recent. In this way the most recent messages will be at the beginning of the list (in this case at the bottom), and the least at the bottom of the list (in this case at the top).

Share:
1,200
Mahesh P
Author by

Mahesh P

I am an enthusiastic Android Developer to learn new Programming things to Grow my coding skills and Improve myself to be better for tomorrow.

Updated on November 24, 2022

Comments

  • Mahesh P
    Mahesh P over 1 year

    What is the best way to use ScrollController in the list for scrolling to the bottom of the list after the listview is rendered data from streambuilder using firestore query stream?

    What is the best place to use scrollcontroller.jumpto method ?

    // initialisation
    ScrollController scrollController=ScrollController();
    
    // inside initstate() and build method with 1000ms delay - not working
    scrollController.jumpTo(scrollController.position.maxScrollExtent);
    
    // widget inside build method
    Expanded(
                    child: StreamBuilder<DocumentSnapshot>(
                        stream: Firestore.instance
                            .collection('Data')
                            .document(widget.dataID)
                            .snapshots(),
                        builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                          print("Called");
                          if (!snapshot.hasData) {
                            return Text("Loading");
                          }
                          var info= snapshot.data.data;
                          if (info!= null &&
                              info["messages"] != null &&
                              info["messages"].length > 0 &&
                              userList.length > 0) {
                            return ListView.builder(
                              controller: scrollController,
                              itemCount: info["challengeReplies"].length,
                              itemBuilder: (BuildContext context, int index) {
    
                                return ChallengeReplyListItem(
                                    currentUserID: widget.currentUserID,
                                    messagesType: info["messages"][index]["messagesType"],
                                    messagesContent: info["messages"][index]["messagesContent"],
                              },
                            );
                          } else if (isLoading) {
                            return Center(
                              child: CircularProgressIndicator(),
                            );
                          } else {
                            return Center(child: Text("No Data Found",style: TextStyle(color: Colors.blueGrey,fontSize: 22,fontWeight: FontWeight.w500),));
                          }
                        }),
                  ),
    

    Can anyone suggest a proper solution to handle a scroll to the bottom of the page after the data gets rendered properly.

    Thanks.