長話短說,現在主流的App都是底部導航按鈕 + Fragment 的方式,Android 原生開發有很多種方式來實現,Flutter 也是。
零、概述
- TabBar + TabBarView
- 相當于 Android 原生
TabLayout + ViewPage
- 有自帶 Material Design 動畫
- 代碼實現簡單
- 支持左右滑動
- 相當于 Android 原生
- BottomNavigationBar + BottomNavigationBarItem
- 相當于Android 原生控件
BottomNavigationBar
- 有自帶 Material Design 動畫
- 代碼實現簡單
- 不支持左右滑動
- 相當于Android 原生控件
- BottomAppBar
- 完全可以自定義
- 代碼量復雜
- 沒有自帶動畫
- CupertinoTabBar
- IOS 風格
一、TabBar + TabBarView
TabBar + TabBarView 的方式非常簡單,相當于 Android 原生中的
TabLayout + ViewPage 方式,并且也支持左右滑動。
如下圖所示:
具體實現代碼如下:
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new TabBarView(controller: controller, children: <Widget>[
new FirstPage(),
new SecondPage(),
new ThirdPage()
]),
bottomNavigationBar: new Material(
color: Colors.blue,
child: new TabBar(
controller: controller,
tabs: <Tab>[
new Tab(text: "首頁", icon: new Icon(Icons.home)),
new Tab(text: "列表", icon: new Icon(Icons.list)),
new Tab(text: "信息", icon: new Icon(Icons.message)),
],
indicatorWeight: 0.1,
),
),
);
}
TabBar
默認是有高度的,但是我找了很久也沒找到 api 去處理,最后使用了一個投機取巧的方法:把 indicatorWeight
的值設置為0.1,也就是把指示器的高度設置為0.1。
二、BottomNavigationBar + BottomNavigationBarItem
這種方式也代碼量非常少,相當于Android原生谷歌推出的 Material Design 風格的控件 BottomNavigationBar
,并且點擊的動畫和效果也是一樣。
如下圖所示:
具體實現代碼如下:
@override
Widget build(BuildContext context) {
return new Scaffold(
body: _children[_currentIndex],
// CupertinoTabBar 是IOS分格
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: onTabTapped,
items: [
BottomNavigationBarItem(
title: new Text("Home"), icon: new Icon(Icons.home)),
BottomNavigationBarItem(
title: new Text("List"), icon: new Icon(Icons.list)),
BottomNavigationBarItem(
title: new Text("Message"), icon: new Icon(Icons.message)),
],
),
);
}
有人會問:Flutter 不是支持 Android 和 IOS 么,我想用 IOS 風格的底部導航欄怎么辦?
很簡單,根據注釋所寫的那樣:只要把 BottomNavigationBar
改成 CupertinoTabBar
就可以了。
如下圖所示:
點擊 Material Design 動畫效果沒有了,圖標上面也出現了一根橫線,并且圖標也會更扁平化。
三、BottomAppBar 自定義
以上兩種方式都是使用系統封裝好的,如果我想完全自定義,不遵循 MD 風格或者 IOS 風格,那就必須使用
BottomAppBar
。
若下圖所示:
代碼如下所示:
Row tabs() {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new Container(
child: IconButton(
icon: Icon(Icons.near_me),
color: _tabColor,
onPressed: () {
setState(() {
_tabColor = Colors.orangeAccent;
_index = 0;
});
},
),
),
IconButton(
icon: Icon(Icons.edit_location),
color: Colors.white,
onPressed: () {
setState(() {
_tabColor = Colors.white;
_index = 1;
});
},
),
],
);
}
中間那個很酷炫的 + 號是 FloatingActionButton
,它們兩可以組合使用,也可以單獨使用,在官網上的解釋如下:
A container that is typically used with Scaffold.bottomNavigationBar, and can have a notch along the top that makes room for an overlapping FloatingActionButton.
Typically used with a Scaffold and a FloatingActionButton.