底部導航 參考
1、普通效果:我們可以通過
Scaffold
的bottomNavigationBar
屬性來設置底部導航,通過Material組件庫提供的BottomNavigationBar
和BottomNavigationBarItem
兩種組件來實現Material風格的底部導航欄。
2、如圖效果:Material組件庫中提供了一個BottomAppBar
組件,它可以和FloatingActionButton
配合實現這種“打洞”效果。
實現如圖“打洞”效果
底部
BottomAppBar
的child
設置爲Row
,並且將Row
用其children
5 等分,中間的位置空出(我的實現方法)。在Scaffold
中設置floatingActionButton
,並且設置floatingActionButtonLocation
爲FloatingActionButtonLocation.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))
(中間的爲空白,itemWidth
爲double 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
爲選中狀態的圖片地址列表。
未選中與選中狀態
Image
和Text
默認設爲未選中圖片及樣式,判斷如果 currentIndex == index
的話,就改爲選中狀態圖片及樣式,這樣構建item的時候就可以。
點擊切換
在每個item的onTap
事件中如果 currentIndex != index
(不處理點擊當前選中的item的情況) 則 currentIndex = index,
調用 setState()
重新build
,body: pages[currentIndex]
即可顯示最新的頁面。