TabBar使用步骤
- 继承StatefulWidget
- 页面必须实现SingleTickerProviderStateMixin
- 页面初始化时,实例化TabController
- 在TabBar和TabBarView组件中指定同一个controller
TabBar属性说明
属性 | 说明 |
tabs | 一系列标签控件 |
controller | 标签选择变化控制器 |
isScrollable | 是否可滚动,默认false |
indicatorColor | 指示器颜色 |
indicatorWeight | 指示器粗细 |
indicator | 指示器 |
indicatorSize | 指示器长短,tab:和tab一样长,label:和标签label 一样长 |
labelColor | 选中标签颜色 |
labelStyle | 选中标签样式 |
labelPadding | 标签内边距 |
unselectedLabelColor | 未选中标签颜色 |
unselectedLabelStyle | 未选中标签样式 |
实现效果
具体实现如下:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TabBarDemo2 extends StatefulWidget {
_TabBarDemo createState() => _TabBarDemo();
}
class _TabBarDemo extends State<TabBarDemo2>
with SingleTickerProviderStateMixin {
TabController _tabController; //控制器
int selectedItem = 0; //当前选择项
@override
void initState() {
_tabController = new TabController(length: 7, vsync: this);
_tabController.addListener(() {
print("index--------"+_tabController.index.toString());
setState(() {
selectedItem = _tabController.index;
});
_tabController.animateTo(_tabController.index);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: [
Container(
height: 50,
margin: EdgeInsets.only(top: 50),
child: TabBar(
isScrollable: true, //是否可用滚动,默认false
controller: _tabController,
onTap: (int index) {
//点击监听
setState(() {
selectedItem = index;
});
},
tabs: [
Text('TAB1', style: TextStyle(color: Colors.black)),
Text('TAB2', style: TextStyle(color: Colors.black)),
Text('TAB3', style: TextStyle(color: Colors.black)),
Text('TAB4', style: TextStyle(color: Colors.black)),
Text('TAB5', style: TextStyle(color: Colors.black)),
Text('TAB6', style: TextStyle(color: Colors.black)),
Text('TAB7', style: TextStyle(color: Colors.black))
]),
),
Expanded(
flex: 1,
child: TabBarView(
controller: _tabController,
children: [
Text(
'TAB1内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
),
Text(
'TAB2内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
),
Text(
'TAB3内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
),
Text(
'TAB4内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
),
Text(
'TAB5内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
),
Text(
'TAB6内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
),
Text(
'TAB7内容',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w700),
)
],
),
),
],
),
),
);
}
}