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:...
)
class MyApp extends StatefulWidget{
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp>{
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>[
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;
});
}
}
class DemoPage extends StatefulWidget {
_DemoPageState createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> 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++;
});
},
),
);
}
}
来源:CSDN
原文:https://blog.csdn.net/weixin_...
版权声明:本文为博主原创文章,转载请附上博文链接!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。