BottomNavigationBar用于在App页面的底部添加导航栏。具体用法让我们一起来看代码吧。主要记住这几点:
-
BottomNavigationBarItem里面设置Icon和label。
-
currentIndex会使选中的图标高亮。
-
要使用户选中该图标时自动跳转页面, 需要在BottomNavigationBar里面设置点击事件onTap(),其中的setState可以实现状态的变化。
-
注意body里面要设置为pages[index]。
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Row Widget Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo')
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Widget> pages = [const Page1(), const Page2(), const Page3()];
int selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('title'),
),
body: pages[selectedIndex],
bottomNavigationBar: BottomNavigationBar(
// type: BottomNavigationBarType.shifting,
backgroundColor: Colors.blue,
currentIndex: selectedIndex,
elevation: 200,
onTap: (index){
setState(() {
selectedIndex = index;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'page1',
backgroundColor: Colors.red
),
BottomNavigationBarItem(icon: Icon(Icons.add_call), label: 'page2'),
BottomNavigationBarItem(icon: Icon(Icons.access_time), label: 'page3')
],
),
);
}
}
class Page1 extends StatelessWidget{
const Page1({super.key});
@override
Widget build(BuildContext context) {
return const Center(child: Text('page1'),);
}
}
class Page2 extends StatelessWidget{
const Page2({super.key});
@override
Widget build(BuildContext context) {
return const Center(child: Text('page2'),);
}
}
class Page3 extends StatelessWidget{
const Page3({super.key});
@override
Widget build(BuildContext context) {
return const Center(child: Text('page3'),);
}
}