使用可折叠应用栏(sliverAppBar)时,如何保留tabView的滚动位置?

7

问题:

在一个tabView滚动到顶部(展示sliverAppBar)时,无法正确地恢复tabView的滚动位置。另一个tabView也会滚动到顶部(失去了之前的滚动位置)。

  • 如果使用普通的应用栏(可折叠应用栏),则不会出现此问题
  • 仅当tabView滚动到顶部时才会出现此问题

问题:

在使用可折叠的应用栏(sliverAppBar)时,如何保留tabView的滚动位置?

代码:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: 2,
      child: Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                title: Text('Example'),
                pinned: true,
                floating: true,
                forceElevated: innerBoxIsScrolled,
                bottom: TabBar(
                  tabs: <Widget>[
                    Tab(text: 'One',),
                    Tab(text: 'Two'),
                  ],
                ),
              ),
            ];
          },
          body: TabBarView(
            children: <Widget>[
              Center(
                key: PageStorageKey<String>('one'),
                child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    return new ListTile(
                      title: new Text('One Item $index'),
                    );
                  },
                ),
              ),
              Center(
                key: PageStorageKey<String>('two'),
                child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    return new ListTile(
                      title: new Text('Two Item $index'),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      )
    );
  }
}

这个功能是由Flutter开发团队添加的,因此现在默认情况下它可以工作。 - Kherel
1个回答

0
这实际上是一个已知问题,目前仍然未解决。尽管有一个变通方法,就像在这个帖子中提到的那样
这里有一个解决方法,使用extended_nested_scroll_view包。使用此方法,我没有遇到任何问题(至少目前为止)。因此,在Flutter修复此问题之前,此解决方法似乎足够。仅在Android上进行了测试。
基本思路是:
  • 使用extended_nested_scroll_view包中的NestedScrollView
  • 将每个选项卡视图包装在带有AutomaticKeepAliveClientMixinwantKeepAlive => trueStatefulWidget
  • 在该StatefulWidget中,将可滚动内容包装在NestedScrollViewInnerScrollPositionKeyWidget
  • innerScrollPositionKeyBuilderNestedScrollViewInnerScrollPositionKeyWidget中使用的关键值必须匹配。

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