flutter - 有没有办法自动滚动到 ListView.builder 中的元素?
问题描述
我的目标是当我点击 GoogleMaps 中的标记时滚动到正确的人。每个标记已经保存了对列表中相应索引的引用,但我不知道如何使列表自行滚动。谢谢你的帮助 :)
解决方案
您可以将 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),
);
推荐阅读
- c# - 如何处理静态 httpclient
- compiler-errors - 编译 ffmpeg:致命错误:ld 以信号 11 终止
- java - 在休眠中从 session.createQuery 获取超过 1 个对象
- git - 使用 Git 的 Sylius / Symfony 标准版本控制流程
- java - 如何使用 CompletableFuture 和 CompletionStage 进行异常处理
- ruby - 从 ruby rspec 运行命令行
- ios - 如何为具有可变高度的 UITableView 下的项目设置约束
- encryption - 在 MudOS LPC 中解密密码
- c++ - (C++) 使用节点/链表时得到不一致的结果。
- scala - Scala 和 Spark 中的“zip”方法是什么?