Flutter 项目实战 01 用BottomNavigationBar自定义底部导航栏
以下是一个简单的Flutter代码示例,展示了如何在Flutter项目中使用BottomNavigationBar
来创建自定义底部导航栏:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// 此处定义应用程序的根Widget
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _currentIndex = 0;
final List<Widget> _pages = [
Icon(Icons.home),
Icon(Icons.search),
Icon(Icons.add_box),
Icon(Icons.favorite),
Icon(Icons.person),
];
void _onItemTapped(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _pages[_currentIndex],
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: _onItemTapped,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.search), title: Text('Search')),
BottomNavigationBarItem(icon: Icon(Icons.add_box), title: Text('Add')),
BottomNavigationBarItem(icon: Icon(Icons.favorite), title: Text('Favorite')),
BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('Profile')),
],
),
);
}
}
这段代码创建了一个包含五个选项卡的底部导航栏,每个选项卡都有图标和文本标题。当用户点击不同的选项卡时,_onItemTapped
函数会更新_currentIndex
状态,从而切换当前显示的页面。这个简单的例子展示了如何在Flutter中使用BottomNavigationBar
,并且如何通过状态管理来响应用户的交互。
评论已关闭