如何保存Flutter Custom Scroll View的滚动位置?

时间:2019-01-23 19:22:47

标签: android ios flutter wrapper android-scrollview

我有一个CustomScrollViewBottomNavigationBar的Material App,在CustomScrollView中,我有SliverAppBar和一页Widget(比如说​​page1,page2等)。 。)代表BottomNavigationBar's当前索引,在每一页Widget上都有SliverList,其中包含一些内容

我试图将键和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
        ],
      ),
    );
  }
}

我的目标是在浏览页面时保存CustomScrollView's滚动状态。

1 个答案:

答案 0 :(得分:2)

在使用PageStorageKey之前,您必须创建那些存储。试试这个简单的临时代码:

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
        ],
      ),
    );
  }
}