Preview:
DINGTALK_IM_2894794293.JPG.JPG
Source code:
class HomeState extends State<MyHomePage> with SingleTickerProviderStateMixin {
TabController mTabController;
PageController mPageController = PageController(initialPage: 0);
List<String> tabList = ['推荐', '热点', '社会', '娱乐', "体育", '美文', '科技', '财经', '时尚'];
var currentPage = 0;
var isPageCanChanged = true;
@override
void initState() {
super.initState();
mTabController = TabController(
length: tabList.length,
vsync: this,
);
mTabController.addListener(() {
if (mTabController.indexIsChanging) {
print(mTabController.index);
onPageChange(mTabController.index, p: mPageController);
}
});
}
onPageChange(int index, {PageController p, TabController t}) async {
if (p != null) {
isPageCanChanged = false;
await mPageController.animateToPage(index,
duration: Duration(milliseconds: 500),
curve: Curves.ease); //等待pageview切换完毕,再释放pageivew监听
isPageCanChanged = true;
} else {
mTabController.animateTo(index);
}
}
@override
void dispose() {
super.dispose();
mTabController.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TabBar & PageView'),
),
body: Column(
children: <Widget>[
Container(
color: Color(0xfff4f5f6),
height: 38.0,
child: TabBar(
isScrollable: true,
controller: mTabController,
labelColor: Colors.red,
unselectedLabelColor: Color(0xff666666),
labelStyle: TextStyle(fontSize: 16.0),
tabs: tabList.map((item) {
return Tab(
text:item,
);
}).toList(),
),
),
Expanded(
child: PageView.builder(
itemCount: tabList.length,
onPageChanged: (index) {
if (isPageCanChanged) {
onPageChange(index);
}
},
controller: mPageController,
itemBuilder: (BuildContext context, int index) {
return Center(
child: Text(
tabList[index],
textScaleFactor: 2,
),
);
},
),
)
],
),
);
}
}