Flutter:滚动到ListView中的小部件 [英] Flutter: Scrolling to a widget in ListView
问题描述
如何滚动到 ListView
中的特殊小部件?
例如,如果我按特定按钮,我想自动滚动到 ListView
中的某些 Container
。
How can I scroll to a special widget in a ListView
?
For instance I want to scroll automatically to some Container
in the ListView
if I press a specific button.
ListView(children: <Widget>[
Container(...),
Container(...), #scroll for example to this container
Container(...)
]);
推荐答案
到目前为止,最简单的解决方案是使用 Scrollable.ensureVisible(context)
一个>。因为它可以为您完成所有工作,并且可以使用任何大小的小部件。使用 GlobalKey
获取上下文。
By far, the easiest solution is to use Scrollable.ensureVisible(context)
. As it does everything for you and work with any widget size. Fetching the context using GlobalKey
.
问题是 ListView
不会渲染不可见的项目。这意味着您的目标极有可能根本不会构建 。这意味着您的目标将没有上下文
;
The problem is that ListView
won't render non-visible items. Meaning that your target most likely will not be built at all. Which means your target will have no context
; preventing you from using that method without some more work.
最后,最简单的解决方案是替换 ListView
通过 SingleChilScrollView
并将您的孩子打包到列
中。示例:
In the end, the easiest solution will be to replace your ListView
by a SingleChilScrollView
and wrap your children into a Column
. Example :
class ScrollView extends StatelessWidget {
final dataKey = new GlobalKey();
@override
Widget build(BuildContext context) {
return new Scaffold(
primary: true,
appBar: new AppBar(
title: const Text('Home'),
),
body: new SingleChildScrollView(
child: new Column(
children: <Widget>[
new SizedBox(height: 160.0, width: double.infinity, child: new Card()),
new SizedBox(height: 160.0, width: double.infinity, child: new Card()),
new SizedBox(height: 160.0, width: double.infinity, child: new Card()),
// destination
new Card(
key: dataKey,
child: new Text("data\n\n\n\n\n\ndata"),
)
],
),
),
bottomNavigationBar: new RaisedButton(
onPressed: () => Scrollable.ensureVisible(dataKey.currentContext),
child: new Text("Scroll to data"),
),
);
}
}
注意:虽然允许轻松滚动至所需项目,仅针对小型预定义列表考虑此方法。至于更大的列表,您会遇到性能问题。
NOTE : While this allows to scroll to the desired item easily, consider this method only for small predefined lists. As for bigger lists you'll get performance problems.
但是可以使 Scrollable.ensureVisible
与 ListView $ c $一起工作c>;虽然需要更多工作。
But it's possible to make Scrollable.ensureVisible
work with ListView
; although it will require more work.
这篇关于Flutter:滚动到ListView中的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!