五、Flutter 實現 ViewPager、bottomNavigationBar 界面切換

一、前言

首先咱們想一下,若是在 Android 中實現 佈局切換,一般的思路是:app

  1. 作一個 viewpager
  2. 一組 Fragment
  3. 每一個 Fragment 綁定一個 xml
  4. 最後填充至 viewpager

二、Flutter 實現

上邊提到的用安卓原生作,思路是很明確,可是代碼量仍是有的,那麼來看一下, Flutter 如何使用 Viewpager 實現的。ide

2.一、建立有狀態 Widget

首先建立有狀態 StatefulWidget,而後構建 state:_ApplicationPageState佈局

class ApplicationPage extends StatefulWidget {
  //@override
  //_ApplicationPageState createState() => new _ApplicationPageState();
   等同於上邊註釋掉的 createState();
    @override
    State<StatefulWidget> createState() {
      // TODO: implement createState
      return _ApplicationPageState();
    }

}

2.二、state

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

Scaffold 有下面幾個主要屬性:
  • appBar:顯示在界面頂部的一個 AppBar,也就是 Android 中的 ActionBar 、Toolbar
  • body:當前界面所顯示的主要內容 Widget
  • bottomNavigationBar: 顯示在頁面底部的導航欄

2.三、navBar和pageview如何聯動?

經過上邊的代碼也能夠發現,pageView有個 onPageChanged 屬性,而且類中定義了一個 _pageChange 方法,設計

經過 pageview 的 pagecontroller 的 animateToPage 方法實現的界面跳轉;code

相關文章
相關標籤/搜索