首页 > 解决方案 > 有没有办法自动滚动到 ListView.builder 中的元素?

问题描述

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

地图和水平列表截图

标签: flutterdart

解决方案


您可以将 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,
         ...,
       ),
    ],
  )
  ...
}

现在,您将能够滚动到您选择的项目:

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),
);

推荐阅读