Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: how to make a list that always scrolls to the bottom?

Tags:

flutter

I am trying to make a list that is basically a log screen. That said, I need the list to keep scrolling to bottom all the time.

How this can be done?

like image 999
Daniel Oliveira Avatar asked Nov 26 '18 14:11

Daniel Oliveira


People also ask

How do you scroll to the bottom automatically Flutter?

Using a ScrollController maxScrollExtent can be used together to smoothly scroll to the bottom of the view: _scrollController. animateTo( _scrollController. position.

How do you make a scrollable list in Flutter?

Just change Column widget to ListView widget — and that's all. Your container becomes scrollable.

How do I scroll to a specific position in ListView in Flutter?

All you have to do is set Global Keys for your widgets and call Scrollable. ensureVisible on the key of your widget you want to scroll to. For this to work your ListView should be a finite List of objects.


2 Answers

Set reverse: true on the ListView widget and reverse the children list.

ListView(
  // Start scrolled to the bottom by default and stay there.
  reverse: true,
  children: widget.children.reversed.toList(growable: false),
),

If you have a very long list and reversing is expensive, you can reverse the index rather than the whole list using ListView.builder

ListView.builder(
    reverse: true,
    itemCount: items.length,
    itemBuilder: (context, index) {
      final reversedIndex = items.length - 1 - index;
      final item = items[reversedIndex];
      return MyWidget(item);
    }
)

I got this from Günter's comment above. Thanks!

like image 104
M. Leonhard Avatar answered Oct 21 '22 17:10

M. Leonhard


I could make this work by using a Timer but probably should have a better way to do this. My workaround was:

  1. Define a ScrollController() and attach it to the listView:
ListView.builder(
      controller: _scrollController,
      itemCount: _logLines.values.length,
      itemBuilder: (context, index) => _getLogLine(index),
    )
  1. Override your page initState method and set a Timer inside it like:
 @override
  void initState() {
      super.initState();
      Timer.periodic(Duration(milliseconds: 100), (timer) {
        if (mounted) {
            _scrollToBottom();
        } else {
          timer.cancel();
        }
      });
    }
  1. Define a method _scrollToBottom() that calls:

    _scrollController.jumpTo(_scrollController.position.maxScrollExtent);

like image 7
Daniel Oliveira Avatar answered Oct 21 '22 16:10

Daniel Oliveira