如何保存Flutter自定义滚动视图的滚动位置?

Tor*_*dze 4 android wrapper ios android-scrollview flutter

我有 Material App 和CustomScrollViewBottomNavigationBarCustomScrollView我有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
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Bam*_*oUA 6

在使用 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
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)