效果图
创建自定义的tabbarcontroller用到 BottomAppBar
直接上代码
/// 当前选中的按钮
int _currentIndex = 0;
late PageController _pageController;
void initState() {
super.initState();
_pageController =PageController(initialPage: _currentIndex, keepPage: true);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
physics: new NeverScrollableScrollPhysics(),
children: _pageList,
controller: _pageController,
),
bottomNavigationBar:BottomAppBar(
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
BottomItem(_currentIndex, 0, 'images/home.png', "首页", 0),
BottomItem(_currentIndex, 1, 'images/cs.png', "分类", 0),
BottomItem(_currentIndex, 2, 'images/sc.png', "购物车",2),
BottomItem(_currentIndex, 3, 'images/my.png', "我的", 0),
],
),
),
);
}
bottomItem(
int selectIndex, int index, var image, String title, int badge) {
TextStyle textStyle = const TextStyle(fontSize: 12.0, color: Colors.grey);
MaterialColor iconColor = Colors.grey;
EdgeInsetsGeometry padding = EdgeInsets.only(top: 8.0);
if (selectIndex == index) {
textStyle =
TextStyle(fontSize: 12.0, color: Theme.of(context).primaryColor);
iconColor = Colors.deepOrange;
}
Widget padItem = const SizedBox();
if (image != null) {
padItem = Padding(
padding: padding,
child: Stack(
children: <Widget>[
Container(
color: Colors.white,
child: Center(
child: Column(
children: <Widget>[
Image.asset(
image,
color: iconColor,width: 20,height: 20,
// size: iconSize,
),
Text(
title,
style: textStyle,
)
],
),
),
),
Positioned(
child: badge > 0
? Container(
width: 12,
height: 12,
child: Center(
child: Text(badge.toString(),
style: const TextStyle(
fontSize: 8.0, color: Colors.white)),
),
decoration: const BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
)
: const Text(""),
right: 40.0,
top: 0.0,
),
],
));
}
Widget item = Expanded(
flex: 1,
child: GestureDetector(
onTap: ()async {
if (index != _currentIndex) {
setState(() {
_pageController.jumpToPage(index);
_currentIndex = index;
});
}
},
child: SizedBox(
height: kBottomNavigationBarHeight , /// 底部高度
child: padItem,
),
),
);
return item;
}