Flutter如何实现底部导航栏
在Flutter中,我想实现一个底部导航栏功能,点击不同的图标可以切换页面。我看官方文档有提到BottomNavigationBar组件,但不知道具体怎么实现页面切换效果。想问下:1)如何正确使用BottomNavigationBar?2)点击不同item时如何关联对应的页面?3)是否需要配合IndexedStack或PageView使用?4) 有没有完整的代码示例可以参考?谢谢!
2 回复
Flutter中实现底部导航栏,主要有两种方式:
- 使用Scaffold的bottomNavigationBar属性
int _currentIndex = 0;
Scaffold(
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: '搜索'),
],
),
body: _buildPage(_currentIndex),
)
- 使用PageView配合底部导航
PageController _pageController = PageController();
Scaffold(
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
_pageController.jumpToPage(index);
},
items: [...],
),
body: PageView(
controller: _pageController,
onPageChanged: (index) {
setState(() {
_currentIndex = index;
});
},
children: [HomePage(), SearchPage()],
),
)
第一种适合简单场景,第二种支持左右滑动切换页面。记得用setState更新状态,保持导航栏和页面同步。
更多关于Flutter如何实现底部导航栏的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,实现底部导航栏通常使用BottomNavigationBar组件,结合PageView或直接切换页面内容。以下是基本实现步骤和示例代码:
1. 基本实现(使用StatefulWidget)
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BottomNavDemo(),
);
}
}
class BottomNavDemo extends StatefulWidget {
@override
_BottomNavDemoState createState() => _BottomNavDemoState();
}
class _BottomNavDemoState extends State<BottomNavDemo> {
int _currentIndex = 0;
final List<Widget> _pages = [
Page1(),
Page2(),
Page3(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '首页',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: '业务',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: '学校',
),
],
),
);
}
}
// 示例页面组件
class Page1 extends StatelessWidget {
@override
Widget build(BuildContext context) => Center(child: Text('首页'));
}
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) => Center(child: Text('业务页'));
}
class Page3 extends StatelessWidget {
@override
Widget build(BuildContext context) => Center(child: Text('学校页'));
}
2. 关键属性说明
currentIndex: 当前选中索引onTap: 点击回调函数items: 导航项数组,每个包含icon和label- 可通过
type属性设置样式(固定/浮动) - 可通过
backgroundColor设置背景色
3. 进阶用法
如需保持页面状态,可使用PageView+AutomaticKeepAliveClientMixin,或使用IndexedStack替代直接切换Widget数组。
这是最常用的底部导航实现方式,简单高效且符合Material Design规范。

