Flutter 使用 BottomAppBar 自定義底部導航(中間浮出按鈕)

底部導航 參考

1、普通效果:我們可以通過ScaffoldbottomNavigationBar屬性來設置底部導航,通過Material組件庫提供的BottomNavigationBarBottomNavigationBarItem兩種組件來實現Material風格的底部導航欄。
2、如圖效果:Material組件庫中提供了一個BottomAppBar組件,它可以和FloatingActionButton配合實現這種“打洞”效果。

實現如圖“打洞”效果

底部BottomAppBarchild設置爲Row,並且將Row用其children 5 等分,中間的位置空出(我的實現方法)。在Scaffold中設置floatingActionButton,並且設置floatingActionButtonLocationFloatingActionButtonLocation.centerDocked

代碼如下:
Scaffold(
      //...省略部分代碼
      floatingActionButton: FloatingActionButton(
          //懸浮按鈕
          child: Icon(Icons.add),
          onPressed: () {}),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      body: pages[currentIndex],
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: <Widget>[
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(0)),
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(1)),
            SizedBox(height: 49, width: itemWidth),
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(2)),
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(3))
          ],
          mainAxisAlignment: MainAxisAlignment.spaceAround,
        ),
        shape: CircularNotchedRectangle(),
      ),
    );

自定義 Item View

上述代碼中,其中4個item都是SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(0))(中間的爲空白,itemWidthdouble itemWidth = MediaQuery.of(context).size.width / 5;)。bottomAppBarItem方法,傳入底部導航item的index,返回Widget,代碼如下:

Widget bottomAppBarItem(int index) {
    //設置默認未選中的狀態
    TextStyle style = TextStyle(fontSize: 12, color: Colors.black);
    String imgUrl = normalImgUrls[index];
    if (currentIndex == index) {
      //選中的話
      style = TextStyle(fontSize: 13, color: Colors.blue);
      imgUrl = selectedImgUrls[index];
    }
    //構造返回的Widget
    Widget item = Container(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Image.asset(imgUrl, width: 25, height: 25),
            Text(
              titles[index],
              style: style,
            )
          ],
        ),
        onTap: () {
          if (currentIndex != index) {
            setState(() {
              currentIndex = index;
            });
          }
        },
      ),
    );
    return item;
  }
變量解釋

pages 爲要顯示的每一頁Widget;
currentIndex 表示當前選中底部item的index;
titles 底部item顯示的文字列表;
normalImgUrls 爲未選中狀態的圖片地址列表;
selectedImgUrls 爲選中狀態的圖片地址列表。

未選中與選中狀態

ImageText默認設爲未選中圖片及樣式,判斷如果 currentIndex == index 的話,就改爲選中狀態圖片及樣式,這樣構建item的時候就可以。

點擊切換

在每個item的onTap 事件中如果 currentIndex != index(不處理點擊當前選中的item的情況) 則 currentIndex = index,調用 setState()重新buildbody: pages[currentIndex]即可顯示最新的頁面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章