何如实现
第一步
- 创建一个StatefulWidget组件,并继承SingleTickerProviderStateMixin抽象类(使用with关键字)
第二步
- 创建TabController参数,并在适当的位中实例化
- TabController在当前state组件中只创建一次,否则报错: XXX is a SingleTickerProviderStateMixin but multiple tickers were created.
//vaync: 继承了SingleTickerProviderStateMixin的对象
//length 标记tabLayout中item的个数
_tabLayoutController = TabController(vsync: this, length: 3);
第三步
- 创建TabBar
TabBar(
//标记是否为滚动模式, false时item平分界面宽度
isScrollable: true,
//与TabBarView绑定的纽带
controller: _tabLayoutController,
//定义tab的item,其中tabs中的item为widget类型,可自定义
tabs: [
Tab(
text: "首页",
),
Tab(
text: "男装",
),
Tab(
text: "童装",
),
],
)
第四步
- 创建TabBarView
TabBarView(
controller: _tabLayoutController,
children: <Widget>[
Text("首页界面"),
Text("男装界面"),
Text("童装界面"),
],
)
controller
- 使得TabBar和TabBarView联动的纽带,且他们的联动不受界面中位置的影响
- 当TabBar和TabBarView同时指定一个controller时,即实现绑定
示例
class TabLayoutAct extends StatefulWidget {
@override
_TabLayoutActState createState() => _TabLayoutActState();
}
class _TabLayoutActState extends State<TabLayoutAct>
with SingleTickerProviderStateMixin {
late TabController _tabLayoutController;
@override
void initState() {
// TODO: implement initState
super.initState();
_tabLayoutController = TabController(vsync: this, length: 3);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Tablayout"),
),
body: Column(
children: [
Container(
height: 70,
color: Colors.pink,
child: TabBar(
//标记是否为滚动模式
isScrollable: true,
//与TabBarView绑定的纽带
controller: _tabLayoutController,
//定义tab的item,其中tabs中的item为widget类型,可自定义
tabs: [
Tab(
text: "首页",
),
Tab(
text: "男装",
),
Tab(
text: "童装",
),
],
),
),
Container(
color: Colors.red,
height: 200,
child: TabBarView(
controller: _tabLayoutController,
children: <Widget>[
Text("首页界面"),
Text("男装界面"),
Text("童装界面"),
],
),
),
],
),
);
}
}