How to save Flutter Custom Scroll View's scroll position?
2,859
Before use PageStorageKey you must create those storage. 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
],
),
);
}
}
Author by
Tornike Kurdadze
Updated on December 09, 2022Comments
-
Tornike Kurdadze over 1 year
I have Material App with
CustomScrollView
andBottomNavigationBar
, inCustomScrollView
I haveSliverAppBar
and one pageWidget
(let say page1, page2 etc...) which representsBottomNavigationBar's
current index, on every pageWidget
there isSliverList
with some contentI have tried to put Keys and
ScrollControllers
insideCustomScrollView
but it doesn't work as I expect, when navigating between pages Scroll position is initial.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. -
NehaK over 2 yearsWorked for me thanksa lot!