NestedScrollView 与 ListView 中的粘性选项卡

2024-05-16

布局按预期工作,但以下情况除外:

当我滚动一页时,第二页也会滚动。没有那么多,但足以掩盖第一个项目。

我可以想象它与 NestedScrollView 有关,但我不知道如何继续。

import 'package:flutter/material.dart';

main(){
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: 2,
      child: new Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              new SliverAppBar(
                title: const Text('Tabs and scrolling'),
                forceElevated: innerBoxIsScrolled,
                pinned: true,
                floating: true,
                bottom: new TabBar(
                  tabs: <Tab>[
                    new Tab(text: 'Page 1'),
                    new Tab(text: 'Page 2'),
                  ],
                ),
              ),
            ];
          },
          body: new TabBarView(
            children: <Widget>[
              _list(),
              _list(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _list(){
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemCount: 250,
      itemBuilder: (context, index){
        return Container(
          color: Colors.grey[200].withOpacity((index % 2).toDouble()),
          child: ListTile(
            title: Text(index.toString()),
          ),
        );
      }
    );
  }
}

为了能够保持两个 ListView 滚动而不互相影响,它们需要定义控制器。

要让 ListView 在选项卡切换之间保持其滚动位置,您需要将它们放在具有 AutomaticKeepAliveClientMixin 的 Widget 中。

以下是您可以执行哪些操作来代替 _list 方法的示例。定义了一个 Stateful Widget,它使用控制器和 AutomaticKeepAliveClientMixin 返回列表:

class ItemList extends StatefulWidget {
  @override
  _ItemListState createState() => _ItemListState();
}

class _ItemListState extends State<ItemList> with AutomaticKeepAliveClientMixin{
  ScrollController _scrollController = ScrollController();
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.zero,
      itemCount: 250,
      itemBuilder: (context, index){
        return Container(
          color: Colors.grey[200].withOpacity((index % 2).toDouble()),
          child: ListTile(
            title: Text(index.toString()),
          ),
        );
      }
    );
  }

  @override
  bool get wantKeepAlive => true;
}

您可以像 TabBarView 中的任何其他小部件一样正常调用它:

TabBarView(
  children: <Widget>[
    ItemList(),
    ItemList(),
  ],
),
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NestedScrollView 与 ListView 中的粘性选项卡 的相关文章

随机推荐