到目前为止,最简单的解决方案是使用Scrollable.ensureVisible(context)
。因为它可以为您完成所有工作,并且可以使用任何大小的小部件。使用获取上下文GlobalKey
。
问题是ListView
不会渲染不可见的项目。这意味着你的目标很可能不会建 在所有 。这意味着你的目标将没有context
; 阻止您在无需进行其他工作的情况下使用该方法。
最后,最简单的解决方案是将您ListView
的替换为,SingleChilScrollView
然后将您的孩子打包成Column
。范例:
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 Sized@R_136_2419@(height: 160.0, width: double.infinity, child: new Card()),
new Sized@R_136_2419@(height: 160.0, width: double.infinity, child: new Card()),
new Sized@R_136_2419@(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"),
),
);
}
}
:虽然这使您可以轻松滚动到所需项目,但仅对小型预定义列表考虑此方法。至于更大的列表,您会遇到性能问题。
但是有可能Scrollable.ensureVisible
与之合作ListView
;尽管这需要更多工作。