注意:无特殊说明,Flutter版本及Dart版本以下:git
- Flutter版本: 1.12.13+hotfix.5
- Dart版本: 2.7.0
BottomNavigationBar 和 BottomNavigationBarItem配合Scaffold控件使用能够实现底部导航效果,相似于微信底部的导航效果,下面是一个简单的底部导航案例:github
Scaffold( bottomNavigationBar: BottomNavigationBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem(title: Text('首页'),icon: Icon(Icons.home)), BottomNavigationBarItem(title: Text('书籍'),icon: Icon(Icons.book)), BottomNavigationBarItem(title: Text('个人'),icon: Icon(Icons.perm_identity)), ], ), );
效果:segmentfault
点击其余2个item时没有反应,添加切换效果:微信
int _currentIndex = 0; BottomNavigationBar( onTap: (int index) { setState(() { _currentIndex = index; }); }, currentIndex: _currentIndex, ...
currentIndex
表明当前显示导航的索引,当前切换时调用onTap
,在onTap
回调中调用setState
方法改变_currentIndex的值达到切换的效果。ide
效果以下:字体
BottomNavigationBar有2种显示模式,其中一种是fixed
效果,前面的展现就是fixed
效果,这也是默认值,另外一种是shifting
效果,动画
BottomNavigationBar( type:BottomNavigationBarType.shifting, selectedItemColor: Theme.of(context).primaryColor, unselectedItemColor: Colors.black, ... }
设置shifting
时须要设置selectedItemColor
和 unselectedItemColor
,效果以下:ui
咱们还能够设置其背景颜色(backgroundColor
)、图标大小(iconSize
)、选中和未选中图标、字体的颜色,大小等。spa
若是导航的图标是本身设计的图标,这时仅仅经过BottomNavigationBar是没法实现咱们想要的效果的,好比微信的导航的效果,虽然选中和未选中也是颜色的区别,但图标不是Icons自带的图标,想要实现切换2个图标须要BottomNavigationBarItem
控件的支持,其中的icon
和activeIcon
分别表明未选中和选中。.net
经过切换导航而改变页面是App中最经常使用的方式,开始构建页面的切换:
int _currentIndex = 0; Widget _currBody = HomePage(); _onTap(int index) { switch (index) { case 0: _currBody = HomePage();; break; case 1: _currBody = BookPage(); break; case 2: _currBody = MyPage(); break; } setState(() { _currentIndex = index; }); } Scaffold( body: _currBody, bottomNavigationBar: BottomNavigationBar( onTap: _onTap, type: BottomNavigationBarType.shifting, selectedItemColor: Theme.of(context).primaryColor, unselectedItemColor: Colors.black, currentIndex: _currentIndex, items: <BottomNavigationBarItem>[ BottomNavigationBarItem(title: Text('首页'), icon: Icon(Icons.home)), BottomNavigationBarItem(title: Text('书籍'), icon: Icon(Icons.book)), BottomNavigationBarItem( title: Text('个人'), icon: Icon(Icons.perm_identity)), ], ), );
Scaffold控件的body
表示导航上面,AppBar下面的页面,HomePage
,BookPage
,MyPage
对应3个导航的页面,背景分别是红、蓝、黄色,效果以下: