问题描述
如何滚动到 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
不会呈现不可见的项目.这意味着您的目标很可能不会被构建.这意味着您的目标将没有 context
;阻止您在不做更多工作的情况下使用该方法.
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
替换为 SingleChildScrollView
,并将您的孩子包装到一个 Column
中.示例:
In the end, the easiest solution will be to replace your ListView
by a SingleChildScrollView
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
data"),
)
],
),
),
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
一起工作;虽然这需要更多的工作.
But it's possible to make Scrollable.ensureVisible
work with ListView
; although it will require more work.
这篇关于Flutter:滚动到 ListView 中的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!