Idris Stack
Idris Stack

Reputation: 566

Push/ animate to the top if you receive any new chat message or Items in a Listview with firestore

How can I animate to top of the ListView, if I receive any new data from firestore , I know the code which animates or pushes to the bottom but where should I place it specifically to ensure that this operation works, whenever there's change in data.?

This is my ListView wrapped with a StreamBuilder :

StreamBuilder(
        stream: commentsStream,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Container();
          }

          return GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
            },
            child: snapshot.data.documents.length != 0
                ? ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    physics: AlwaysScrollableScrollPhysics(),
                    controller: _scrollController,
                    reverse: true,
                    itemBuilder: (context, index) {
                      return CommentsTile(
                        message: snapshot.data.documents[index].data["message"],
                        isAuthor: int.parse(snapshot
                                    .data.documents[index].data["isAuthor"]
                                    .toString()
                                    .trim()) ==
                                0
                            ? false
                            : true,
                        value: int.parse(snapshot
                            .data.documents[index].data["isAuthor"]
                            .toString()
                            .trim()),
                        name: snapshot.data.documents[index].data["username"],
                        date: formatDate(
                            snapshot.data.documents[index].data["time"]),
                      );
                    })
                : Center(
                    child: Text(
                      "No comments",
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 15,
                          fontStyle: FontStyle.italic),
                    ),
                  ),
          );
        },
      );

Upvotes: 1

Views: 309

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17123

Use the onData parameter of the .listen method for streams. Put any code you need to run when the Stream updates in onData.

The .listen call should be done in the initState method if the surrounding widget is stateful.

See this for more information on the listen method.

Edit:

To implement in your code add

commentsStream.listen(() {
  onReloadNewChat();
});

to your initState method immediately following

setState(() {
  commentsStream = value
});

Upvotes: 1

Related Questions