1

I am dynamically adding item to ListView. When I add new item, it should scroll to bottom like in WhatsApp app.

I am doing it like this

setState(() {
  _textList.add(text);
});
_scrollController.animateTo( //Should run after rebuild
  _scrollController.position.maxScrollExtent,
  duration: const Duration(milliseconds: 300),
  curve: Curves.easeInOut,
);

Since setState() runs asynchronously, maxScrollExtent is not updated, which is resulting in scroll until previous item only.

How to do await for setState. Is there anyway to achieve this. Also I don't want do call Future.delayed.

Here is my full code DartPad.

Thanks.

Crazy Lazy Cat
  • 13,595
  • 4
  • 30
  • 54

1 Answers1

0

You can try this method as the first line in your build method.

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

  });
Harsha pulikollu
  • 2,386
  • 15
  • 28