StatefulWidget需要保持状态,切换页面后,Widget树不会dispose,保持原有的状态:
- 混入AutomaticKeepAliveClientMixin抽象类,
- 重写方法wantKeepAlive
- 在build方法中 调用父类的方法 super.build(context) ```dart
class ChatPage extends StatefulWidget { @override _ChatPageState createState() => _ChatPageState(); }
class _ChatPageState extends State
@override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); return Scaffold( appBar: AppBar( title: Text(‘微信’), backgroundColor: WeChatThemeColor,
),);
} }
使用bottomNavigationBar的情况下,要保持pages的状态,需使用PageController```dartimport 'package:flutter/material.dart';import 'pages/chat_page.dart';import 'pages/friends/friends_page.dart';import 'pages/mine_page.dart';import 'pages/discover/discover_page.dart';class RootPage extends StatefulWidget {@override_RootPageState createState() => _RootPageState();}class _RootPageState extends State<RootPage> {int _currentIndex = 0;final PageController _controller = PageController(initialPage: 0);@overrideWidget build(BuildContext context) {return Scaffold(body: PageView(controller: _controller,physics: NeverScrollableScrollPhysics(), //不滚动children: [ChatPage(),FriendsPage(),DiscoverPage(),MinePage()],),bottomNavigationBar: BottomNavigationBar(onTap: (index) {setState(() {_currentIndex = index;_controller.animateToPage(index, duration: Duration(microseconds: 100), curve: Curves.easeIn);});},selectedFontSize: 12.0, //选中的字体大小currentIndex: _currentIndex,fixedColor: Colors.green,type: BottomNavigationBarType.fixed,items: [BottomNavigationBarItem(icon: Image.asset('images/tabbar_chat.png',height: 20,width: 20,),activeIcon: Image.asset('images/tabbar_chat_hl.png',height: 20,width: 20,),title: Text('微信'),),BottomNavigationBarItem(icon: Image.asset('images/tabbar_friends.png',height: 20,width: 20,),activeIcon: Image.asset('images/tabbar_friends_hl.png',height: 20,width: 20,),title: Text('通讯录'),),BottomNavigationBarItem(icon: Image.asset('images/tabbar_discover.png',height: 20,width: 20,),activeIcon: Image.asset('images/tabbar_discover_hl.png',height: 20,width: 20,),title: Text('发现'),),BottomNavigationBarItem(icon: Image.asset('images/tabbar_mine.png',height: 20,width: 20,),activeIcon: Image.asset('images/tabbar_mine_hl.png',height: 20,width: 20,),title: Text('我的'),),],),);}}
