[英]How to save Flutter Custom Scroll View's scroll position?
I have Material App with CustomScrollView
and BottomNavigationBar
, in CustomScrollView
I have SliverAppBar
and one page Widget
(let say page1, page2 etc...) which represents BottomNavigationBar's
current index, on every page Widget
there is SliverList
with some content我有带有
CustomScrollView
和BottomNavigationBar
Material App,在CustomScrollView
我有SliverAppBar
和一个页面Widget
(比如 page1、page2 等...),它代表了BottomNavigationBar's
当前索引,在每个页面Widget
上都有带有一些内容的SliverList
I have tried to put Keys and ScrollControllers
inside CustomScrollView
but it doesn't work as I expect, when navigating between pages Scroll position is initial.我试图将 Keys 和
ScrollControllers
放在CustomScrollView
但它没有按我预期的那样工作,当在页面之间导航时滚动位置是初始的。
class WrapperPage extends StatefulWidget {
@override
_WrapperPage createState() => _WrapperPage();
}
class _WrapperPage extends State<WrapperPage> {
int _curIndex = 0;
List<Widget> _pages;
List<PageStorageKey> _keys;
List<ScrollController> _ctrls;
@override
void initState() {
_pages = [
// some pages pages
];
_keys = List();
_ctrls = List();
for (int i = 0; i < 5; ++i) {
_keys.add(PageStorageKey('scroll$i'));
_ctrls.add(ScrollController());
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
key: _keys[_curIndex],
controller: _ctrls[_curIndex],
slivers: <Widget>[SliverAppBar(), _pages[_curIndex]],
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int i) {
setState(() {
_curIndex = i;
});
},
currentIndex: _curIndex,
items: [
// some buttons
],
),
);
}
}
My goal is to save CustomScrollView's
scroll state while navigating pages.我的目标是在导航页面时保存
CustomScrollView's
滚动状态。
Before use PageStorageKey you must create those storage.在使用 PageStorageKey 之前,您必须创建这些存储。 Try this simple scratch code:
试试这个简单的暂存代码:
class _WrapperPage extends State<WrapperPage> {
int _curIndex = 0;
List<Widget> _pages;
final bucket = PageStorageBucket(); // Create storage bucket
@override
void initState() {
_pages = [];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body:
// Wrap target widget with PageStorageBucket here.
PageStorage(
bucket: bucket,
child: CustomScrollView(
// Use `runtimeType` as unique value for key
key: PageStorageKey(_pages[_curIndex].runtimeType.toString()),
controller: _ctrls[_curIndex],
slivers: <Widget>[SliverAppBar(), _pages[_curIndex]],
),
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int i) {
setState(() {
_curIndex = i;
});
},
currentIndex: _curIndex,
items: [
// some buttons
],
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.