首先咱們想一下,若是在 Android 中實現 佈局切換,一般的思路是:app
上邊提到的用安卓原生作,思路是很明確,可是代碼量仍是有的,那麼來看一下, Flutter 如何使用 Viewpager 實現的。ide
首先建立有狀態 StatefulWidget,而後構建 state:_ApplicationPageState佈局
class ApplicationPage extends StatefulWidget { //@override //_ApplicationPageState createState() => new _ApplicationPageState(); 等同於上邊註釋掉的 createState(); @override State<StatefulWidget> createState() { // TODO: implement createState return _ApplicationPageState(); } }
Scaffold 實現了基本的紙墨設計佈局結構。因此咱們 new Scaffold 而後 return 便可。ui
class _ApplicationPageState extends State<ApplicationPage> { int _currentPageIndex = 0; var _pageController = new PageController(initialPage: 0); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("我是AppBar"), centerTitle: true, ), body: new PageView.builder( onPageChanged:_pageChange, controller: _pageController, itemBuilder: (BuildContext context,int index){ return index==1?new Text("我是第一頁"):new Text("我是第二頁"); }, itemCount: 2, ), bottomNavigationBar: new BottomNavigationBar(items: [ BottomNavigationBarItem( icon: new Icon(Icons.category), title: new Text("首頁")), BottomNavigationBarItem( icon: new Icon(Icons.message), title: new Text("個人")), ], currentIndex: _currentPageIndex, onTap: onTap, ), ); } // bottomnaviagtionbar 和 pageview 的聯動 void onTap(int index) { // 過pageview的pagecontroller的animateToPage方法能夠跳轉 _pageController.animateToPage(index, duration: const Duration(milliseconds: 300), curve: Curves.ease); } void _pageChange(int index) { setState(() { if (_currentPageIndex != index) { _currentPageIndex = index; } }); } }
關於上邊有幾個方法:spa
經過上邊的代碼也能夠發現,pageView有個 onPageChanged 屬性,而且類中定義了一個 _pageChange 方法,設計
經過 pageview 的 pagecontroller 的 animateToPage 方法實現的界面跳轉;code