I have a problem with automatic scrolling down to recently added content. For example, this code doesn't scroll to just added ListTile, but to (n-1) one:

class _HomePageState extends State<HomePage> {
  ScrollController _controller = ScrollController();
  List<Widget> tiles = [];
  int n = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          setState(
            () {
              n++;
              tiles.add(ListTile(title: Text('ListTile $n')));
            },
          );
          return _controller.animateTo(
            _controller.position.maxScrollExtent,
            curve: Curves.linear,
            duration: Duration(milliseconds: 500),
          );
        },
        child: ListView.builder(
            controller: _controller,
            itemCount: tiles.length,
            itemBuilder: (context, index) => tiles[index]),
      ),
    );
  }
}

I think that the problem is that I update the State and the scroll position within the same step simultaneously, but can't bend my mind how to do it other way.

Any advice?


Solution 1: Amir

try this

class _HomePageState extends State<HomePage> {
  ScrollController _controller = ScrollController();
  List<Widget> tiles = [];
  int n = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          setState(
            () {
              n++;
              tiles.add(ListTile(title: Text('ListTile $n')));
            },
          );
          Future.delayed(Duration(milliseconds: 100), (){
              _controller.animateTo(
                _controller.position.maxScrollExtent,
                curve: Curves.linear,
                duration: Duration(milliseconds: 500),
              );
          });
            },
            child: ListView.builder(
                controller: _controller,
                itemCount: tiles.length,
                itemBuilder: (context, index) => tiles[index]),
          ),
        );
      }
    }