[英]Is there a way to automatically scroll to an element in ListView.builder?
My goal is to scroll to the correct person when I tap the marker in GoogleMaps.我的目标是在我点击 GoogleMaps 中的标记时滚动到正确的人。 Each marker has already saved a reference to the respective index in the list, but i don't know how I can make the list scroll by itself.每个标记都已经保存了对列表中相应索引的引用,但我不知道如何让列表自行滚动。 Thanks for any help :)谢谢你的帮助 :)
You can assign a GlobalKey
to the item you want to scroll to and make use of ScrollPosition.ensureVisible
.您可以为要滚动到的项目分配GlobalKey
并使用ScrollPosition.ensureVisible
。
You need the global key in order to access the RenderObject
of your widget.您需要全局密钥才能访问小部件的RenderObject
。
You will need to either store this global key as a variable in your StatefulWidget
(preferrably).您需要将此全局键作为变量存储在StatefulWidget
(最好)。
ScrollController
You will also need to store a scroll controller in order to scroll to the position of your list view.您还需要存储一个滚动控制器,以便滚动到列表视图的位置。
Here is how you would do it in the State
of your widget:以下是在小部件的State
中执行此操作的方法:
final itemKey = GlobalKey();
final scrollController = ScrollController();
@override
void dispose() {
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Return your widget tree in here.
// I am only showing the ListView section.
...
ListView(
...,
controller: scrollController,
// You can also use a builder list view or w/e else.
// You only need to supply the GlobalKey to exactly one item.
children: <Widget>[
SomeWidget(
key: itemKey,
...,
),
],
)
...
}
Now, you will be able to scroll to your selected item:现在,您将能够滚动到您选择的项目:
scrollController.position.ensureVisible(
itemKey.currentContext.findRenderObject()!,
alignment: 0.5, // How far into view the item should be scrolled (between 0 and 1).
duration: const Duration(seconds: 1),
);
You can also use Scrollable
widget to scroll to specific widget:您还可以使用Scrollable
小部件滚动到特定的小部件:
Scrollable.ensureVisible(
itemKey.currentContext,
duration: const Duration(milliseconds: 500)
);
itemKey is a GlobalKey
which is assigned to key
property of a widget itemKey 是分配给小部件的key
属性的GlobalKey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.