1

我了解如何在 PageView 中应用 keepAlive。但是当我来到flutter_pagewise(https://pub.dev/packages/flutter_pagewise)时,我对如何实现保持PagewiseListView的状态感到困惑,因为在PageView中更改页面导致此PagewiseListView再次构建。任何人都可以告诉我一个解决方案吗?

我的 PageView 是:

 PageView(
                children: <Widget>[
                    CardListView(),
                    Container(
                        color: Colors.cyan,
                    ),
                ],

            ),

我的 CardListView 是:

class CardListView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _CardListViewState();
}

class _CardListViewState extends State<CardListView>
    with AutomaticKeepAliveClientMixin<CardListView> {
  static const int PAGE_SIZE = 10;

  var postsMap = Map<int, List<PostModel>>();

  @override
  Widget build(BuildContext context) {

    super.build(context);

    void updatePostsMap(int pageIndex, List<PostModel> posts) {
      setState(() {
        postsMap[pageIndex] = posts;
      });
    }

    return PagewiseListView(
        pageSize: PAGE_SIZE,
        itemBuilder: this._itemBuilder,
        pageFuture: (pageIndex) {
          if (postsMap.containsKey(pageIndex)) {
            print('found');
            return Future.value(postsMap[pageIndex]);
          } else {
            print('load');
            return BackendService.getPosts(pageIndex * PAGE_SIZE, PAGE_SIZE)
                .then((List<PostModel> posts){
                  updatePostsMap(pageIndex, posts);
                  return posts;
            });
          }
        }
    );

  }
4

0 回答 0