我有带有CustomScrollViewBottomNavigationBar的Material App,在CustomScrollView中,我有SliverAppBar和一页Widget(请说page1,page2等...),它表示BottomNavigationBar's当前索引,在每一页Widget上都有SliverList,其中包含一些内容

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

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

最佳答案

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

10-06 06:33