flutter 底部导航栏的制作
时间: 2023-09-05 07:08:34 浏览: 44
Flutter 底部导航栏可以使用 `BottomNavigationBar` 组件来实现。
首先,需要在 `StatefulWidget` 的 `build` 方法中创建 `BottomNavigationBar` 组件并设置它的 `items` 属性,该属性接受一个包含每个导航项的 `BottomNavigationBarItem` 对象的列表。
例如:
```dart
class MyBottomNavigationBar extends StatefulWidget {
@override
_MyBottomNavigationBarState createState() => _MyBottomNavigationBarState();
}
class _MyBottomNavigationBarState extends State<MyBottomNavigationBar> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Bottom Navigation Bar'),
),
body: Container(
child: Center(
child: Text('This is the $_currentIndex tab'),
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (int index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
);
}
}
```
在这个例子中,我们创建了一个 `_currentIndex` 变量来存储当前选中的导航项的索引。在 `build` 方法中,我们创建了一个包含三个导航项的 `BottomNavigationBar` 组件,并将其传递给 `bottomNavigationBar` 属性。每个导航项都由一个 `BottomNavigationBarItem` 对象表示,它包含一个图标和一个标签。
我们还为 `BottomNavigationBar` 组件设置了 `currentIndex` 属性,以确定当前选中的导航项。当用户点击某个导航项时,我们使用 `onTap` 回调函数来更新 `_currentIndex` 变量,并调用 `setState` 方法来重建界面。
最后,我们将 `BottomNavigationBar` 组件放在 `Scaffold` 组件的 `bottomNavigationBar` 属性中,并将其他内容放在 `Scaffold` 组件的 `body` 属性中。