通过IndexedStack + Scaffold中的bottomNavigationBar来实现
关键代码如下:
int index = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(children: _pages,//IndexedStack控制页面显示
index: index,
),
bottomNavigationBar: BottomNavigationBar(//导航
items: _bottomNavigationBarItems,//导航item
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.green,
selectedFontSize: 12,
unselectedFontSize: 12,
currentIndex: index,
onTap: (idx){
setState(() {
index = idx;//切换显示的页面索引值
});
},
),
);
}
IndexedStack
IndexedStack是Stack的子类,Stack组件可以将子组件层叠显示,根据子组件的顺序依次向上叠加,而IndexedStack只显示指定的子组件
导航item的代码如下:
class YQBottomNavigationBarItem extends BottomNavigationBarItem{
final String label;
final String iconName;
final double iconSize;
final String iconBasePath;
YQBottomNavigationBarItem(
this.iconName,
this.label,
{
this.iconSize = 30,
this.iconBasePath = "assets/images/tabbar"
}
) : super(
label: label,
icon: Image.asset("$iconBasePath/$iconName.png",
width: iconSize,
gaplessPlayback: true,
),
activeIcon: Image.asset("$iconBasePath/${iconName}_active.png",
width: iconSize,
gaplessPlayback: true,
),
);
}
点击item进行切换的时候,item的图标闪烁,怎么解决?
导航item中,需要注意gaplessPlayback属性。如果导航item中的图标是图片组件,而不是Icon组件的话,那么在页面加载完毕,首次点击导航item进行切换的时候,可能会出现item图标闪烁的情况。将gaplessPlayback的值设置为true,可以解决。
点击导航item的时候,会出现水波纹效果(点击的时候出现单黑色的圆圈,然后消失),怎么消除这种效果呢?
将MaterialApp的ThemeData中的splashColor设置为透明色即可,如下:
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
visualDensity: VisualDensity.adaptivePlatformDensity,
splashColor: Colors.transparent//设置为透明色
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
导航item的数量≥4的时候,只显示item的图标,而不显示文字,怎么解决?
将BottomNavigationBar的type设置为BottomNavigationBarType.fixed即可。