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?
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?
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!
I found WidgetsBinding.instance.addPostFrameCallback
extremely useful, especially in situations like this where you need some post build processing. In this case it solved the issue as follows:
final ScrollController _sc = ScrollController();
WidgetsBinding.instance.addPostFrameCallback((_) => {_sc.jumpTo(_sc.position.maxScrollExtent)});
controller: _sc,
I was also building a logger viewer. Works like a charm.
I could make this work by using a Timer
but probably should have a better way to do this.
My workaround was:
ScrollController()
and attach it to the listView:ListView.builder(
controller: _scrollController,
itemCount: _logLines.values.length,
itemBuilder: (context, index) => _getLogLine(index),
)
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();
}
});
}
Define a method _scrollToBottom()
that calls:
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);