我的目标是在我点击 GoogleMaps 中的标记时滚动到正确的人。每个标记都已经保存了对列表中相应索引的引用,但我不知道如何让列表自行滚动。谢谢你的帮助 :)

cre*_*not 10
您可以将 a 分配给GlobalKey要滚动到的项目并使用ScrollPosition.ensureVisible。
您需要全局密钥才能访问RenderObject小部件的 。
您需要将此全局键作为变量存储在您的StatefulWidget(最好)中。
ScrollController您还需要存储一个滚动控制器,以便滚动到列表视图的位置。
以下是您在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,
...,
),
],
)
...
}
Run Code Online (Sandbox Code Playgroud)
现在,您将能够滚动到您选择的项目:
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),
);
Run Code Online (Sandbox Code Playgroud)
您还可以使用Scrollable小部件滚动到特定小部件:
Scrollable.ensureVisible(
itemKey.currentContext,
duration: const Duration(milliseconds: 500)
);
Run Code Online (Sandbox Code Playgroud)
itemKey 是GlobalKey分配给key小部件的属性
| 归档时间: |
|
| 查看次数: |
2822 次 |
| 最近记录: |