Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
              );
            },
          );
        }
      }
    );
  }
like image 698
CrustyWang Avatar asked Jun 20 '19 12:06

CrustyWang


People also ask

How do I create a dynamic list view in flutter?

You can make a dynamically created ListView by using the ListView. builder() constructor. This will create the ListView items only when they need to be displayed on the screen. It works like an Android RecyclerView but is a lot easier to set up.


1 Answers

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,
              );
            },
          ),
        );
      }
like image 85
anmol.majhail Avatar answered Oct 16 '22 17:10

anmol.majhail