页面保持状态,不重绘,在app中很重要,比如看着朋友圈/热门微博,看到一半,需要切换到其他tab设置点东西,再切换回来,这个时候肯定不需要页面重绘,然后从头开始看吧,而是希望直接接着前面的状态继续看。
这样我们就需要用到页面保持状态,使他不销毁不重绘。
关键词:
BottomNavigationBar+PageView+AutomaticKeepAliveClientMixin
要点
子页面的class
class _HomePageState with AutomaticKeepAliveClientMixin{//要点1
@override
bool get wantKeepAlive => true;//要点2
Widget build(BuildContext context){
super.build(context);//要点3
}
}
光上面其实还不够,还需要搭配其他Widget使用,例如BottomNavigationBar+PageView活着TabBar+TabbarView,这样页面才不会销毁。
//PageView是重点的重点
Scaffold(
body:PageView.builder(
physics: NeverScrollableScrollPhysics(),//禁止页面左右滑动切换
controller: _pageController,
onPageChanged: _pageChanged,
itemCount: _pages.length,
itemBuilder: (context,index)=>_pages[index]
)
bottomNavigationBar:...
)
完整代码
frame.dart
class MyApp extends StatefulWidget{
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State{
var _pages = [HomePage(),ListViewDemo(),DemoPage(),UserListPage()];
int _tabIndex = 0;
var _pageController =PageController();
@override
void dispose() {
super.dispose();
_pageController.dispose();
}
Widget build(BuildContext context){
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.pinkAccent
),
home:Scaffold(
body:PageView.builder(//要点1
physics: NeverScrollableScrollPhysics(),//禁止页面左右滑动切换
controller: _pageController,
onPageChanged: _pageChanged,//回调函数
itemCount: _pages.length,
itemBuilder: (context,index)=>_pages[index]
),
bottomNavigationBar:BottomNavigationBar(
items: [
BottomNavigationBarItem(title:Text('主页'),icon: Icon(Icons.home)),
BottomNavigationBarItem(title:Text('商城'),icon: Icon(Icons.shopping_basket)),
BottomNavigationBarItem(title:Text('测试'),icon: Icon(Icons.pageview)),
BottomNavigationBarItem(title:Text('我的'),icon: Icon(Icons.account_box)),
],
onTap: (index){
print('onTap');
_pageController.jumpToPage(index);
},
type:BottomNavigationBarType.fixed,
currentIndex: _tabIndex,
),
)
);
}
void _pageChanged(int index){
print('_pageChanged');
setState(() {
if(_tabIndex != index)
_tabIndex = index;
});
}
}
demo_page.dart
class DemoPage extends StatefulWidget {
_DemoPageState createState() => _DemoPageState();
}
class _DemoPageState extends State with AutomaticKeepAliveClientMixin{//要点1
int _count = 0;
@override
bool get wantKeepAlive => true;//要点2
@override
Widget build(BuildContext context) {
super.build(context);//要点3
return Scaffold(
appBar: AppBar(title:Text('Demo Page')),
body: Center(child:Text('当前计数:$_count')),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
setState(() {
_count++;
});
},
),
);
}
}