Flutter-bottomNavigationBar+PageView布局

KeepAliveWrapper

主要避免在切换Tab时,会刷新当前页面的所有状态,每个页面都会重新刷新

这里引入一个组件,能同时在列表中和列表外使用,并可以缓存它

class KeepAliveWrapper extends StatefulWidget {
  const KeepAliveWrapper({
    Key? key,
    this.keepAlive = true,
    required this.child,
  }) : super(key: key);
  final bool keepAlive;
  final Widget child;

  @override
  _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child;
  }

  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    if(oldWidget.keepAlive != widget.keepAlive) {
      
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
}

示例

创建page时,将page用 KeepAliveWrapper 包装一下

List _views = [
    KeepAliveWrapper(
      keepAlive: true,
      child: Page(),
    ),
    KeepAliveWrapper(
      keepAlive: true,
      child: Page(),
    ),
    KeepAliveWrapper(
      keepAlive: true,
      child: Page(),
    ),
];

创建 PageView 时,禁止左右滑动(根据需求而定)

PageController _controller = new PageController();
PageView.builder(
      ///禁止左右滑动
      physics: NeverScrollableScrollPhysics(),
      itemBuilder: (context, index) {
        return _views[index];
      },
      itemCount: _views.length,
      controller: _controller,
)

bottomNavigationBar点击更新切换当前显示page

if (index != _currIndex) {
         setState(() {
         _currIndex = index;
         _controller.jumpToPage(index);
    });
}

 

相关:

https://book.flutterchina.club/chapter6/keepalive.html#_6-8-1-automatickeepalive

posted @ 2022-04-30 17:01  macroK  阅读(435)  评论(0编辑  收藏  举报