Home > Software engineering >  flutter stuck at end of list i can't scroll top
flutter stuck at end of list i can't scroll top

Time:01-11

    class ChatList extends ConsumerStatefulWidget {
  final String recieverUserId;
  const ChatList({Key? key, required this.recieverUserId}) : super(key: key);
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _ChatListState();
}

class _ChatListState extends ConsumerState<ChatList> {
  final ScrollController messageController = ScrollController();

  @override
  void dispose() {
    super.dispose();
    messageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ref.read(chatMessagesProvider(widget.recieverUserId)).when(
      data: (data) {
        return ListView.builder(
          controller: messageController,
          physics: ClampingScrollPhysics(),
          itemCount: data.length,
          itemBuilder: (context, index) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              messageController
                  .jumpTo(messageController.position.maxScrollExtent);
            });
            final messageData = data[index];
            if (!messageData.isSeen &&
                messageData.recieverid == ref.watch(userProvider)!.uid) {
              ref.read(chatControllerProvider).setChatMessageSeen(
                  context, widget.recieverUserId, messageData.messageId);
            }
            if (ref.watch(userProvider)!.uid == messageData.senderId) {
              return MyMessageCard(
                isSeen: messageData.isSeen,
                type: messageData.type,
                message: messageData.text,
                date: DateFormat.Hm().format(messageData.timeSent),
              );
            }
            return SenderMessageCard(
              type: messageData.type,
              message: messageData.text,
              date: DateFormat.Hm().format(messageData.timeSent),
            );
          },
        );
      },
      error: (error, stackTrace) {
        return ErrorText(error: error.toString());
      },
      loading: () {
        return Loader();
      },
    );
  }
}

enter image description here

flutter goes all the way in listview automatically, but I can't scroll up I changed the physics property, I changed the location of addpostframecallback, but I still can't scroll the list up. I want it to scroll to the end when clicked on this conversation and then scroll up

CodePudding user response:

Try to go to end of list on condition. in your State class create a bool var shouldScrollDown = true

Then add condition to your postframe callback

if(shouldScrollDown) {
  WidgetsBinding.instance.addPostFrameCallback((_) {
    messageController.jumpTo(messageController.position.maxScrollExtent);
   });
   shouldScrollDown = false;
}
  • Related