1、前言
首先我們想一下,如果在 Android 中實現 布局切換,通常的思路是:
- 做一個 viewpager
- 一組 Fragment
- 每個 Fragment 綁定一個 xml
- 最后填充至 viewpager
2、Flutter 實現
上邊提到的用安卓原生做,思路是很明確,但是代碼量還是有的,那么來看一下, Flutter 如何使用 Viewpager 實現的。
2.1、創建有狀態 Widget
首先創建有狀態 StatefulWidget,然后構建 state:_ApplicationPageState
class ApplicationPage extends StatefulWidget { //@override //_ApplicationPageState createState() => new _ApplicationPageState(); 等同於上邊注釋掉的 createState(); @override State<StatefulWidget> createState() { // TODO: implement createState return _ApplicationPageState(); } }
2.2、state
Scaffold 實現了基本的紙墨設計布局結構。所以我們 new Scaffold 然后 return 即可。
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; } }); } }
關於上邊有幾個方法:
Scaffold 有下面幾個主要屬性:
-
appBar:顯示在界面頂部的一個 AppBar,也就是 Android 中的 ActionBar 、Toolbar
-
body:當前界面所顯示的主要內容 Widget
-
bottomNavigationBar: 顯示在頁面底部的導航欄
2.3、navBar和pageview如何聯動?
通過上邊的代碼也可以發現,pageView有個 onPageChanged 屬性,並且類中定義了一個 _pageChange 方法,
通過 pageview 的 pagecontroller 的 animateToPage 方法實現的界面跳轉;

