[英]how can I scroll list view to the bottom in flutter
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?我有一个 flutter 应用程序包含一个列表视图构建器(聊天页面) 我需要将页面滚动到页面末尾到最后一条消息?
You will need to create a scrollController and pass that to the ListView and run a code like this:您需要创建一个 scrollController 并将其传递给 ListView 并运行如下代码:
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();
}
}
Setting reverse: true to ListView widget will bring the newest element at the bottom.将 reverse: true 设置为 ListView 小部件会将最新的元素置于底部。 With this, you can achieve a chat timeline easily.
有了这个,您可以轻松实现聊天时间线。
ListView.builder(
reverse: true,
itemBuilder: (context, index) => _chatCell(),
)
Initialize the object of ScrollController class in the initState method.在initState方法中初始化ScrollController class的object。
Remember:- 1) Call the super.initState();记住:- 1) 调用 super.initState(); at the top of the initState method.
在 initState 方法的顶部。 2) ListView should be connected with the scroll controller's object.
2) ListView 应与滚动控制器的 object 连接。
WidgetsBinding.instance.addPostFrameCallback((_) { scrollController.jumpTo(scrollController.position.maxScrollExtent); });
WidgetsBinding.instance.addPostFrameCallback((_) { scrollController.jumpTo(scrollController.position.maxScrollExtent); });
Then, add the above code at the top of the build method.然后,在 build 方法的顶部添加上面的代码。 It will scroll automatically to the bottom of the list view of messages.
它将自动滚动到消息列表视图的底部。
Perfect way to do this is by adding完美的方法是添加
reverse: true
to the ListView.builder()
and change the way you give data the list view.到
ListView.builder()
并更改为列表视图提供数据的方式。 Like this.像这样。
Instead of retrieving normally, reverse it and give it to the list view builder.与其正常检索,不如将其反转并将其提供给列表视图构建器。
<List> _messages = [...];
_messages.reversed.toList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.