Home > Software design >  Flutter - how to scroll to the bottom of a listview?
Flutter - how to scroll to the bottom of a listview?

Time:10-26

I use this code to scroll:

WidgetsBinding.instance?.addPostFrameCallback((_) => _scrollToEnd());

_scrollToEnd() method is:

_scrollController.animateTo(
  _scrollController.position.maxScrollExtent,
  duration: const Duration(
    milliseconds: 200,
  ),
  curve: Curves.easeInOut,
);

Imagine this as a normal chat screen. It scrolls to the bare bottom if the messages are in 1 line. But as soon as a message gets to 2 lines it struggles to scroll to the bare bottom. The more rows of a message the less it scrolls to the bottom.

This is how it looks like when i enter the chat:

enter image description here

But if i scroll down further this is the bottom of the chat:

enter image description here

I noticed there's also a case when:

  1. I enter the chat.
  2. It scrolls down like on the first image.
  3. If i tap anywhere on the screen, it continues to scroll to the bare bottom of the listview like on the second image.

Why does this happen and how do i fix this?

Thank you

CodePudding user response:

what i did, use a listView and reverse true and in children use the list of map.reversed, i am giving you my code example below.

ListView(
          reverse: true,
          children: controller.listMessageData.reversed
           .map((e) => Container(child: Text(e.title));

CodePudding user response:

Use ScrollController for that it works smooth and simple to use

ScrollController _scrollController = new ScrollController();

Add controller to LisView like this :

 ListView.builder(controller: _scrollController,)

In your initState to scroll to bottom when navigating to this screen

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          curve: Curves.easeOut,
          duration: const Duration(milliseconds: 500),
        );
      }
    });
}
  • Related