BottomNavigationBar+PageView+AutomaticKeepAliveClientMixinapp
要点ide
子页面的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是重点的重点ui
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_...
版权声明:本文为博主原创文章,转载请附上博文连接!.net