调用setState后如何防止Flutter应用滚动到顶部? [英] How to prevent Flutter app from scrolling to top after calling setState?
问题描述
我在 SingleChildScrollView
中有一个 ExpansionPanelList
。每当我打开面板并因此调用 setState
时, SingleChildScrollView
都会滚动回到顶部。如何防止这种情况发生?
I have an ExpansionPanelList
inside a SingleChildScrollView
. Whenever I (un)fold a panel and therefore call setState
, the SingleChildScrollView
scrolls back to the top. How can I prevent this?
@override
Widget build(BuildContext context) {
final _scaffoldKey = new GlobalKey<ScaffoldState>();
return new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(
title: new Text(widget.title),
),
body: new SingleChildScrollView(
child: new ExpansionPanelList(
children: <ExpansionPanel>[
// panels
],
expansionCallback: (int index, bool isExpanded) {
setState(() {
// toggle expanded
});
},
), // ExpansionPanelList
), // SingleChildScrollView
); // Scaffold
}
此答案建议使用带有 keepScrollOffset的自定义
设置为 ScrollController
true
,但这是默认值,因此将其显式设置为 true
不会更改任何内容。
This answer suggests using a custom ScrollController
with keepScrollOffset
set to true
, however this is the default value and setting it explicitly to true
therefore does not change anything.
推荐答案
这是因为您使用的是新的 Key
每次重建窗口小部件(setState)时。
That's because you are using a new Key
every time you rebuild the widget (setState).
要解决您的问题,只需将下面的代码移至 build
方法之外
To fix your issue just move the code below outside the build
method
final _scaffoldKey = new GlobalKey<ScaffoldState>();
就像这样:
final _scaffoldKey = new GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(
title: new Text(widget.title),
),
这篇关于调用setState后如何防止Flutter应用滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!