Flutter教程实现底部导航栏切换
在Flutter中实现底部导航栏切换时遇到了一些问题:
-
按照官方文档设置了
BottomNavigationBar
,但切换页面时内容区域没有更新,始终显示第一个页面,如何正确绑定导航栏的点击事件? -
导航栏切换时页面会重新加载,导致之前页面的状态丢失,有没有办法保持每个子页面的状态不被销毁?
-
如果想在导航栏切换时加入动画效果(比如渐隐或滑动),应该如何实现?
-
自定义导航栏图标和文字样式后,选中状态的高亮效果失效了,该怎么同时兼顾自定义样式和交互反馈?
3 回复
要实现底部导航栏切换,首先创建一个包含 BottomNavigationBar
的 Flutter 页面。首先定义底部导航栏的选项和对应的页面:
int _selectedIndex = 0;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
final List<Widget> _widgetOptions = <Widget>[
Text('首页'),
Text('分类'),
Text('购物车'),
Text('我的'),
];
return Scaffold(
appBar: AppBar(title: Text('底部导航栏')),
body: Center(child: _widgetOptions[_selectedIndex]),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
BottomNavigationBarItem(icon: Icon(Icons.category), label: '分类'),
BottomNavigationBarItem(icon: Icon(Icons.shopping_cart), label: '购物车'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
);
}
这段代码实现了底部导航栏的基本功能,通过 _onItemTapped
方法更新当前选中的索引,并动态切换显示不同的页面内容。