且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带ListViews的NestedScrollView中的粘滞选项卡

更新时间:2023-11-04 11:15:16

要能够使两个ListView滚动而不互相影响,它们需要具有已定义的控制器.

To be able to keep the two ListViews to scroll without affecting each other they need to have defined controllers.

要使ListView在选项卡切换之间保持其滚动位置,您需要将它们放置在带有AutomaticKeepAliveClientMixin的小部件中.

To have the ListViews maintain their scroll position between tab switching you need to have them in a Widget with AutomaticKeepAliveClientMixin.

这是您可以代替_list方法执行的示例.定义了一个有状态的小部件,该状态小部件可以同时使用控制器和AutomaticKeepAliveClientMixin返回您的列表:

Here's an example of what you can do instead of your _list method. Defined a Stateful Widget that returns your lists using both controllers and the 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中的其他任何小部件一样正常调用它:

You can just call it normally like any other widget inside your TabBarView:

TabBarView(
  children: <Widget>[
    ItemList(),
    ItemList(),
  ],
),