效果如下:
简单解释一下吧,
创建两个数组,一个存放tab的icon 和 标题,另一个存放对应的状态界面的函数名;
int currentIndex = 0; //接收点击到的页面数 var currentPage ;//用来接收要展示的对应界面
BottomNavigationBar
首先,bottomNavigationBar 是属于 Scaffold 中的一个位于底部的控件。通常和 BottomNavigationBarItem 配合使用
BottomNavigationBar构造方法
BottomNavigationBar({
Key key,
@required this.items,
this.onTap,
this.currentIndex = 0,
BottomNavigationBarType type,
this.fixedColor,
this.iconSize = 24.0,
})
BottomNavigationBar({
Key key,
@required this.items,
this.onTap,
this.currentIndex = 0,
BottomNavigationBarType type,
this.fixedColor,
this.iconSize = 24.0,
})
属性 | 值类型 | 说明 |
---|---|---|
items | BottomNavigationBarItem类型的List | 底部导航栏的显示项 |
onTap | ValueChanged < int > | 点击导航栏子项时的回调 |
currentIndex | int | 当前显示项的下标 |
type | BottomNavigationBarType | 底部导航栏的类型,有fixed和shifting两个类型,显示效果不一样 |
fixedColor | Color | 底部导航栏type为fixed时导航栏的颜色,如果为空的话默认使用ThemeData.primaryColor |
iconSize | double | BottomNavigationBarItem icon的大小 |
BottomNavigationBar中属性比较简单,下面我们来看一下BottomNavigationBarItem
BottomNavigationBarItem
底部导航栏要显示的Item,有图标和标题组成
构造方法:
const BottomNavigationBarItem({
@required this.icon,
this.title,
Widget activeIcon,
this.backgroundColor,
})
属性 | 值类型 | 说明 |
---|---|---|
icon | Widget | 要显示的图标控件,一般都是Iocn |
title | Widget | 要显示的标题控件,一般都是Text |
activeIcon | Widget | 选中时要显示的icon,一般也是Icon |
backgroundColor | Color | BottomNavigationBarType为shifting时的背景颜色 |
void main() {
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
//去掉右上角的debug贴纸
debugShowCheckedModeBanner: true,
theme: ThemeData(
primarySwatch: Colors.amber,),
home: IndexPage(),
);
}
}
class IndexPage extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _IndexPageState();
}
}
class _IndexPageState extends State<IndexPage> {
final List<BottomNavigationBarItem> bootomTabs =[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.home),
label:'首页'
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.loop),
label:'发现'
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.add_circled_solid),
label:'发布'
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.conversation_bubble),
label:'消息'
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.person),
label:'会员中心'
),
];
final List tabBodies = [
Home(),
Faxian(),
Fabu(),
Xiaoxi(),
Mine(),
];
int currentIndex = 0;
var currentPage ;
@override
void initState() {
// TODO: implement initState
currentPage = tabBodies[currentIndex];
super.initState();
}
@override
Widget build(BuildContext context) {
ScreenUtil.init(context,width: 750,height: 1334);
return Scaffold(
backgroundColor: Colors.black,//Color.fromARGB(244,25,5,1),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: currentIndex,
items: bootomTabs,
onTap: (index){
setState(() {
currentIndex = index;
currentPage = tabBodies[currentIndex];
});
},
),
body: currentPage,
);
}
}