flutter tabbar 切换到某一个index 的时候,把index 重置到指定的位置,
举例 切换到1 重置到 0
代码如下
如果不需要动画 可以用 jumpToPage
TabController _tabController;
PageController _pageController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
_pageController = PageController(initialPage: 1);
}
@override
void dispose() {
_tabController.dispose();
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Tab Bar'),
bottom: TabBar(
controller: _tabController,
onTap: (index) {
if(index==1){
// index = 0;
_tabController.index = 0;
_pageController.animateToPage(
0,
duration: Duration(milliseconds: 30),
curve: Curves.easeInOut,
);
return;
}
_pageController.animateToPage(
index,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
},
tabs: [
Tab(
text: 'Tab 1',
),
Tab(
text: 'Tab 2',
),
],
),
),
body: PageView(
controller: _pageController,
onPageChanged: (index) {
print('当前页面: $index');
if(index==1){
// index = 0;
_tabController.index = 0;
_pageController.animateToPage(
0,
duration: Duration(milliseconds: 30),
curve: Curves.easeInOut,
);
return;
}
_tabController.animateTo(index);
_pageController.animateToPage(
index,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
},
children: [
// 第一个页面的内容
// ...
Center(child: Text("1"),),
Center(child: Text("2"),)
],
),
bottomNavigationBar: TabBar(
controller: _tabController,
onTap: (index) {
_pageController.animateToPage(
index,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
},
tabs: [
Tab(
text: 'Tab 1',
),
Tab(
text: 'Tab 2',
),
],
),
);
网友评论