BottomNavigationBar组件是Flutter中用于创建底部导航栏的组件。通过BottomNavigationBar,我们可以在页面底部添加多个导航项,并为每个导航项指定对应的图标和文本。
下面是一个简单的示例,演示如何在Flutter应用中使用BottomNavigationBar组件:
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _selectedIndex = 0;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter BottomNavigationBar Demo'),
),
body: Center(
child: Text('Selected Index: $_selectedIndex'),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
);
}
}
void main() {
runApp(MaterialApp(
title: 'Flutter BottomNavigationBar Demo',
home: MyApp(),
));
}
通过以上步骤,我们就创建了一个简单的Flutter应用,该应用包含一个底部导航栏,点击导航项时会更新页面中心显示的文本内容。读者可以根据自己的需求,进一步定制BottomNavigationBar组件的样式和功能,例如修改图标、文本、颜色等属性。希望这个教程对读者有所帮助!