TabBar+TabController+TabBarView

Posted by アライさん on 2020年10月13日

TabController.index从0开始
注意:当TabController重新创建时(比如页签变化了),这时希望让TabController跳回第一页时,需要指定initialIndex为1(非0)。

1
2
3
4
//将initialIndex设置为1
TabController( initialIndex: 1, length: typeList.length, vsync: this);
//然后再跳转到0
TabController.animateTo(0);

如果将initialIndex设置为0,animateTo(0)不会执行,导致TabBarView不切换。

TabController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class _FollowingGlobalPageState extends State<FollowingGlobalPage>
with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState();
// 创建Controller
_tabController = TabController(initialIndex: 0,length: type.lenght, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
}

TabBar页签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//圆角页签
TabBar(
isScrollable: true,
controller: controller,
labelColor: Colors.white,
unselectedLabelColor: CommonColors.mainRed,
indicator: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(28))),
color: CommonColors.mainRed,
),
tabs: typeList
.map<Widget>((text) => Container(
alignment: Alignment.center,

height: ScreenUtil().setHeight(56),
child:Text(
text,
style: TextStyle(
fontSize: ScreenUtil().setSp(26),
),
),
))
.toList(),
),),

TabBarView页签中的内容

1
2
3
4
5
6
TabBarView(
controller: typeController,
children: typeList
.map<Widget>((type) => _createPage(type))
.toList(),
),