这些事情要考虑:
- 使用选项卡控制器并检查 indexIsChanging
- 在 Tab 中使用用于颜色更改的小部件包装文本
- 移除 labelPadding
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
TabController tabController;
List<Color> tabBackground;
List colors = [Colors.red, Colors.green, Colors.yellow];
Random random = Random();
@override
void initState() {
super.initState();
tabController = TabController(length: 3, vsync: this);
tabBackground = [Colors.blue, Colors.pink, Colors.cyan];
tabController.addListener(() {
if (tabController.indexIsChanging) {
setState(() {
tabBackground[tabController.index] = colors[random.nextInt(3)];
});
}
});
}
@override
void dispose() {
tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.pink,
bottom: TabBar(
labelPadding: EdgeInsets.zero,
labelColor: Colors.yellow,
indicatorColor: Colors.black,
controller: tabController,
tabs: [
Tab(
child: Container(
alignment: Alignment.center,
constraints: BoxConstraints.expand(),
color: tabBackground[0],
child: Text(
'Tab 1',
style: TextStyle(
color: Colors.white,
),
),
),
),
Tab(
child: Container(
alignment: Alignment.center,
constraints: BoxConstraints.expand(),
color: tabBackground[1],
child: Text(
'Tab 2',
style: TextStyle(
color: Colors.white,
),
),
),
),
Tab(
child: Container(
alignment: Alignment.center,
constraints: BoxConstraints.expand(),
color: tabBackground[2],
child: Text(
'Tab 3',
style: TextStyle(
color: Colors.white,
),
),
),
),
],
),
title: Text('Tabs Demo'),
),
body: TabBarView(
controller: tabController,
children: List<Widget>.generate(3, (int index) {
return Center(
child: Text(index.toString()),
);
}),
),
);
}
}