目前移動(dòng)開發(fā)tab切換是一個(gè)很通用的功能,F(xiàn)lutter 通過Material 庫提供了很方便的API來使用tab切換。
效果圖

image
創(chuàng)建TabController
TabBarView和TabBar都有一個(gè)tabController的參數(shù)
TabBarView和Tab是就由TabController來控制同步的,點(diǎn)擊了某個(gè)tab后,要同步的顯示對(duì)應(yīng)的TabBarView。TabController的創(chuàng)建有兩種形式,一種是使用系統(tǒng)的DefaultTabController,這種方式很簡單,只要在Scaffold上面再套一層DefaultTabController就可以了。這種方式下,TabBarView會(huì)自動(dòng)去查找這個(gè)tabController,如果找不到就會(huì)報(bào)錯(cuò)。
第二種是自己定義一個(gè)TabController.實(shí)現(xiàn)SingleTickerProviderStateMixin
創(chuàng)建TabBar
TabBar哪里都可以創(chuàng)建,但是在AppBar里面有一個(gè)bottom參數(shù)可以接收TabBar,會(huì)放在導(dǎo)航欄的下面。
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),
),
],
),
創(chuàng)建Tab對(duì)應(yīng)的內(nèi)容Widget
tab對(duì)應(yīng)的內(nèi)容view要放在TabBarView里面。如下:
new TabBarView(
controller: _tabController,
children: <Widget>[
new Center(child: new Text('自行車')),
new Center(child: new Text('船')),
new Center(child: new Text('巴士')),
],
),
兩種方式的完整代碼
第一種實(shí)現(xiàn)代碼如下:
@override
Widget build(BuildContext context) {
return new DefaultTabController(
length: 3,
child: 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(
children: <Widget>[
new Center(child: new Text('自行車')),
new Center(child: new Text('船')),
new Center(child: new Text('巴士')),
],
),
),
);
}
第二種代碼如下:
class TabBarDemoState extends State<TabBarDemo>
with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: 3);
}
@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('巴士')),
],
),
);
}
關(guān)于學(xué)習(xí)
flutter的學(xué)習(xí)文章及代碼都整理在這個(gè)github倉庫里