Scaffold方法下提供 bottomNavigationBar属性用于定义应用程序的底部导航栏,主要由按钮加文字组成, 可以实现点击按钮切换不同的页面,显示在Scaffold的底部区域.
该属性值为BottomNavigationBar类型组件,BottomNavigationBar组件包含下表所示的常用属性。
BottomNavigationBar
BottomNavigationBar构造方法
BottomNavigationBar({
required this.items,
this.onTap,
this.currentIndex = 0,
this.elevation,
this.type,
Color? fixedColor,
this.backgroundColor,
this.iconSize = 24.0,
Color? selectedItemColor,
this.unselectedItemColor,
})
BottomNavigationBarItem
BottomNavigationBarItem的构造方法
const BottomNavigationBarItem({
required this.icon,
this.label,
Widget? activeIcon,
this.backgroundColor,
this.tooltip,
})
实现底部导航
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_play/bottomNavigationBar.dart';
/*启动页*/
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(), //主题
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _bottomNavigationIndex = 0; //底部导航的索引
@override
Widget build(BuildContext context) {
return Scaffold(
body: pages[_bottomNavigationIndex], //页面切换
bottomNavigationBar: _bottomNavigationBar() //底部导航
);
}
//底部导航-样式
BottomNavigationBar _bottomNavigationBar(){
return BottomNavigationBar(
items: items(), //底部导航-图标和文字的定义,封装到函数里
currentIndex: _bottomNavigationIndex,
onTap: (flag) {
setState(() {
_bottomNavigationIndex = flag; //使用底部导航索引
});
}, //onTap 点击切换页面
fixedColor: Colors.blue, //样式:图标选中时的颜色:蓝色
type: BottomNavigationBarType.fixed, //样式:选中图标后的样式是固定的
);
}
}
创建组件bottomNavigationBar.dart
import 'package:flutter/material.dart';
import 'package:flutter_play/index.dart';
import 'package:flutter_play/find.dart';
import 'package:flutter_play/shop.dart';
import 'package:flutter_play/home.dart';
//底部导航页-切换页面
final pages = [
IndexPage(), //首页
FindPage(), //发现页
ShopPage(), //商城页
HomePage() //个人主页
];
//底部导航-图标和文字定义
List<BottomNavigationBarItem> items(){
return [
const BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '首页',
),
const BottomNavigationBarItem(
icon: Icon(Icons.find_in_page),
label: '发现',
),
const BottomNavigationBarItem(
icon: Icon(Icons.shop),
label: '商城',
),
const BottomNavigationBarItem(
icon: Icon(Icons.local_activity),
label: '我的',
),
];
}