效果图:
代码如下:
import 'package:flutter/material.dart';
class BottomTabBarWidget extends StatefulWidget {
final Color backgroundColor;
final Color indicatorColor;
final List<Widget> tabItems;
final List<Widget> pageViews;
final PageController pageController;
BottomTabBarWidget(this.backgroundColor, this.indicatorColor, this.tabItems,
this.pageViews, this.pageController);
@override
_BottomTabBarWidgetState createState() => _BottomTabBarWidgetState(
this.backgroundColor,
this.indicatorColor,
this.tabItems,
this.pageViews,
this.pageController);
}
class _BottomTabBarWidgetState extends State<BottomTabBarWidget>
with SingleTickerProviderStateMixin { ///实现 SingleTickerProviderStateMixin 该接口的目的是防止每次滑动都重新绘制页面
Color _backgroundColor;
Color _indicatorColor;
List<Widget> _tabItems;
List<Widget> _pageViews;
_BottomTabBarWidgetState(this._backgroundColor, this._indicatorColor,
this._tabItems, this._pageViews, this._pageController)
: super();
TabController _tabController;
PageController _pageController;
@override
void initState() {
super.initState();
///初始化时创建控制器
///通过 with SingleTickerProviderStateMixin 实现动画效果。
_tabController = new TabController(vsync: this, length: _tabItems.length);
}
@override
void dispose() {
///页面销毁时,销毁控制器
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _pageController,
children: _pageViews,
onPageChanged: (index) {
_tabController.animateTo(index); /// 滑动跳转(即左右滑动)(点击跳转需外部实现)
},
),
bottomNavigationBar: Material(
color: _backgroundColor,
///tabBar控件
child: new TabBar(
///必须有的控制器,与pageView的控制器同步
controller: _tabController,
///每一个tab item,是一个List<Widget>
tabs: _tabItems,
///tab底部选中条颜色
indicatorColor: _indicatorColor,
),
));
}
}
点击跳转实现(比如从第一页直接跳转到第三页),在每一个TabBar 的 Item 的 onPress 属性中编写如下代码:
onPressed: () {
pageController.jumpTo(MediaQuery.of(context).size.width * 1);
},