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