1

I would like to make my chat messages to scroll down every time I open a someone's chat. I have tried with jumpTo(), but i didn't worked out. Maybe someone have any clue how to make it work? Thank you in advance!

Here is the code snippet

Widget ChatMessageList() {
return StreamBuilder(
  stream: chatMessageStream,
  builder: (context, snapshot) {
    return snapshot.hasData
        ? ListView.builder(
            controller: controller,
            itemCount: snapshot.data.docs.length,
            itemBuilder: (context, index) {
              return MessageTile(
                snapshot.data.docs[index].data()["message"],
                snapshot.data.docs[index].data()["sendBy"] ==
                    Constants.myName,

              );
              controller.jumpTo(controller.position.maxScrollExtent);
            },
          )
        : Container();},);}

before

after working ScrollController

Chorche
  • 85
  • 3
  • 9

2 Answers2

4

ListView.builder() has a parameter named reverse. This is false by default, if you change it to true you probably achieve what you want to achieve.

ListView.builder(
      reverse: true,
);
Stijn2210
  • 812
  • 6
  • 14
2

If your main goal is to get the latest messages first you can use Reverse for the Snapshot

final messages = snapshot.data.docs.reversed;

I hope you got the point

matr0s
  • 99
  • 5
  • I'm sorry, but i didn't fully understand. Can you give a link example or explain it. – Chorche Feb 24 '21 at 14:47
  • I can't get a quick and exact example, but I did similar in my app: * You have a variable where you save you reversed Snapshot: final messages = snapshot.data.docs.reversed; * Get necessary data and put in separate variables: List messageBubbles = []; for (var message in messages) { final messageText = message.data()['text']; final messageSender = message.data()['sender']; final currentUser = logedInUser.email; ....... – matr0s Feb 24 '21 at 15:01
  • ......... final messageBubble = MessageBubble( sender: messageSender, text: messageText, isMe: currentUser == messageSender, ); messageBubbles.add(messageBubble); } – matr0s Feb 24 '21 at 15:01
  • 1
    Not sure if it's clear. I Will try to share more data once have more time – matr0s Feb 24 '21 at 15:02
  • Now i got the point, I've tried it, but I'd got error on 'MessageBubble' "The name 'MessageBubble' isn't a type so it can't be used as a type argument." Take your time :) – Chorche Feb 24 '21 at 18:26
  • 1
    MessageBubble - that's my custom widget, I used four UI elements. You can actually ignore it and just show Snapshot data in your widget (I guess it is MesageTile in your case) – matr0s Feb 24 '21 at 19:01
  • Dyakuyu @matr0s, for your time and help! – Chorche Feb 24 '21 at 21:35