flutterdartautoscrollflutter-listview

Flutter how to create List view autoscrolling?


I'm trying to make a ListView that auto-scrolls to the newest data point. I tired to do this by making a _scrollToBottom function that uses the .jumpTo method.

But i get a blank screen in the app, and 'child.parentData != null': is not true. in the debug console.

Any suggestions on how i can implement auto-scrolling?

Here is the relevant portions of my current code:

ScrollController _scrollController = ScrollController();

_scrollToBottom(){  _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

@override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: DataShareWidget.of(context).stream,
      builder: (BuildContext context, AsyncSnapshot snapshot){
        if(snapshot.hasError){ return Text(snapshot.error);}
        if(snapshot.hasData){
          _dataFormat(snapshot.data);
          return ListView.builder(
            itemCount: _listViewData.length,
            controller: _scrollController,
            reverse: true,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              _scrollToBottom();
              return ListTile(
                title: AutoSizeText(_listViewData[index], maxLines: 2),
                dense: true,
              );
            },
          );
        }
      }
    );
  }

Solution

  • What you need is to call _scrollToBottom() method once the list is built fully.

    Modification is your code (without StreamBuilder):

          ScrollController _scrollController = ScrollController();
        
          _scrollToBottom() {
            _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
          }
          
          @override
          void initState() {
            super.initState();
          }
        
          @override
          Widget build(BuildContext context) {
            WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom()); 
            return Scaffold(
              body: ListView.builder(
                itemCount: 50,
               // itemCount: _listViewData.length,
                controller: _scrollController,
                reverse: true,
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('Yo Dummy Text $index'),
                    // title: AutoSizeText(_listViewData[index], maxLines: 2),
                    dense: true,
                  );
                },
              ),
            );
          }