how can I scroll list view to the bottom in flutter
Solution 1
You will need to create a scrollController and pass that to the ListView and run a code like this:
class SampleList extends StatefulWidget {
@override
_SampleListState createState() => _SampleListState();
}
class _SampleListState extends State<SampleList> {
ScrollController _scrollController;
@override
Widget build(BuildContext context) {
return ListView.builder(
controller: _scrollController,
itemBuilder: (_, index) => ListTile(
title: Text(
index.toString(),
),
),
);
}
void scrollToBottom() {
final bottomOffset = _scrollController.position.maxScrollExtent;
_scrollController.animateTo(
bottomOffset,
duration: Duration(milliseconds: 1000),
curve: Curves.easeInOut,
);
}
@override
void initState() {
_scrollController = ScrollController();
super.initState();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
}
Solution 2
Setting reverse: true to ListView widget will bring the newest element at the bottom. With this, you can achieve a chat timeline easily.
ListView.builder(
reverse: true,
itemBuilder: (context, index) => _chatCell(),
)
Solution 3
Initialize the object of ScrollController class in the initState method.
Remember :- 1) Call the super.initState(); at the top of the initState method. 2) ListView should be connected with the scroll controller's object.
WidgetsBinding.instance.addPostFrameCallback((_) { scrollController.jumpTo(scrollController.position.maxScrollExtent); });
Then, add the above code at the top of the build method. It will scroll automatically to the bottom of the list view of messages.
Solution 4
Perfect way to do this is by adding
reverse: true
to the ListView.builder()
and change the way you give data the list view. Like this.
Instead of retrieving normally, reverse it and give it to the list view builder.
<List> _messages = [...];
_messages.reversed.toList();
Husamuldeen
Updated on December 19, 2022Comments
-
Husamuldeen over 1 year
I have a flutter app contain a list view builder (chat page) I need to scroll the page to the end of the page to the last message?