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

4
我有一个带有CustomScrollViewBottomNavigationBar的Material应用程序,在CustomScrollView中我有一个SliverAppBar和一个页面Widget(比如page1,page2等...),它表示BottomNavigationBar的当前索引,在每个页面Widget上都有一些内容的SliverList
我尝试将Keys和ScrollControllers放入CustomScrollView中,但它并不像我期望的那样工作,当在页面之间导航时,滚动位置是初始的。请注意保留HTML标记。
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的滚动状态。


尝试保存当前状态,然后在调用initState()时重新加载它。 - user1462442
当导航到新页面时,我是否应该保存偏移量并在返回时恢复偏移量? - Tornike Kurdadze
是的,我认为有些状态不应该默认为持久状态。我认为你应该使用更全局的状态保存并稍后恢复它。 - user1462442
哦,刚刚我发现在滚动状态丢失的页面上我有流构建器。 - Tornike Kurdadze
1个回答

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

对我有用,非常感谢! - NehaK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接