Flutter AppBar中自定义TabBar实现顶部Tab切换
Flutter的AppBar组件中加入TabBar组件可以实现顶部Tab切换
TabBar常见属性:
属性 | 描述 |
---|---|
tabs | 显示的标签内容,一般使用Tab对象,也可以是其他的Widget |
controller | TabController对象 |
isScrollable | 是否可滚动 |
indicatorColor | 指示器颜色 |
indicatorWeight | 指示器高度 |
indicatorPadding | 底部指示器的Padding |
indicator | 指示器decoration,例如边框等 |
indicatorSize | 指示器大小计算方式,TabBarIndicatorSize.label跟文字等宽,TabBarIndicatorSize.tab跟每个tab等宽 |
labelColor | 选中label颜色 |
labelStyle | 选中label的Style |
labelPadding | 每个label的padding值 |
unselectedLabelColor | 未选中label颜色 |
unselectedLabelStyle | 未选中label的Style |
一、Flutter AppBar中自定义TabBar的第一种实现方法
import 'package:flutter/material.dart';
class AppBardemoPage extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('FlutterDemo'),
bottom: TabBar(
tabs: <Widget>[
Tab(text: "热门"),
Tab(text: "推荐")
]
)),
body: TabBarView(
children: <Widget>[
ListView(
children: <Widget>[
ListTile(title: Text("这是第一个tab")),
ListTile(title: Text("这是第一个tab")),
ListTile(title: Text("这是第一个tab"))
],
),
ListView(
children: <Widget>[
ListTile(title: Text("这是第二个tab")),
ListTile(title: Text("这是第二个tab")),
ListTile(title: Text("这是第二个tab"))
],
)
],
),
),
),
);
}
}
二、Flutter AppBar中自定义TabBar的另一种实现方法
import 'package:flutter/material.dart';
class AppBardemoPage extends StatefulWidget {
AppBardemoPage({Key key}) : super(key: key);
_AppBardemoPageState createState() => _AppBardemoPageState();
}
class _AppBardemoPageState extends State<AppBardemoPage> with SingleTickerProviderStateMixin {
TabController _tabController;
[@override](/user/override)
void dispose() {
_tabController.dispose();
super.dispose();
}
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: 3);
}
[@override](/user/override)
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('顶部tab切换'),
bottom: new TabBar(
tabs: <Widget>[
new Tab(
icon: new Icon(Icons.directions_bike),
),
new Tab(
icon: new Icon(Icons.directions_boat),
),
new Tab(
icon: new Icon(Icons.directions_bus),
),
],
controller: _tabController,
),
),
body: new TabBarView(
controller: _tabController,
children: <Widget>[
new Center(child: new Text('自行车')),
new Center(child: new Text('船')),
new Center(child: new Text('巴士')),
],
),
);
}
}