flutter BottomNavigationBar切换页面保持状态

1、tabBar对应的每个页面实现AutomaticKeepAliveClientMixin,值改为true

2、tabBar对应的每个页面的build()方法调用super.build(context);

3、PageView中设置physics: const NeverScrollableScrollPhysics(), //禁止滑动

return Scaffold(
   body: PageView.builder(
     controller: _controller,
     physics: const NeverScrollableScrollPhysics(), //禁止滑动
     itemCount: list.length,
     itemBuilder: (context, index) => list[index],
   ),
   bottomNavigationBar: initBottomNavigationBar(),
 );
///设置页面
class SettingPage extends StatefulWidget{
  const SettingPage({Key? key}):super(key: key);

  @override
  State<SettingPage> createState() =>SettingState();

}

///实现AutomaticKeepAliveClientMixin
class SettingState extends State<SettingPage> with AutomaticKeepAliveClientMixin{

  @override
  Widget build(BuildContext context) {
    super.build(context);  //调用super.build(context);
    return Scaffold(
      appBar: AppBar(title: const Text("设置中心"),),
    );
  }

  @override
  bool get wantKeepAlive => true;  //改为true
}

具体实现

详细代码查看Flutter BottomNavigationBar带有页面切换示例

猜你喜欢

转载自blog.csdn.net/xiaopihair123/article/details/125525039