綜述
在Material的設(shè)計(jì)準(zhǔn)則里面窗价,tabs是一個(gè)常用的模塊胜卤。Flutter里面包含了 material library創(chuàng)建tab布局的簡便方法
一益缎、指引
- 創(chuàng)建一個(gè)
TabController
- 創(chuàng)建tab頁
- 為每個(gè)tab創(chuàng)建內(nèi)容
1. 創(chuàng)建一個(gè) TabController
為了使tab起作用有缆,我們需要保持選中的tab和相關(guān)內(nèi)容同步。這就是 TabController
的職責(zé)锉矢。
我們可以手動(dòng)創(chuàng)建TabController
,也可以使用DefaultTabController
小部件齿尽。使用DefaultTabController
是最簡單的選項(xiàng)沽损,因?yàn)樗鼘槲覀儎?chuàng)建一個(gè)TabController
,并使它可用于所有子類Widget循头。
DefaultTabController(
// The number of tabs / content sections we need to display
length: 3,
child: // See the next step!
);
2. 創(chuàng)建tab頁
現(xiàn)在我們已經(jīng)有個(gè)一個(gè)TabController
,我們可以TabBar
Widget去使用創(chuàng)建我們的tab绵估。在這個(gè)示例中,我們將會(huì)在一個(gè)AppBar
下.創(chuàng)建一個(gè)包含3個(gè)Tab
Widgets 的TabBar
卡骂。
DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
),
),
);
默認(rèn)情況下国裳,TabBar
在Widget樹中查找最近的DefaultTabController
。如果是手動(dòng)創(chuàng)建的TabController
全跨,則需要將其傳遞到“TabBar”缝左。
3. 為每個(gè)tab創(chuàng)建內(nèi)容
既然我們有了選項(xiàng)卡,那么我們就需要在選擇選項(xiàng)卡時(shí)顯示相關(guān)的內(nèi)容。因此渺杉,我們將使用TabBarView
Widget.
備注:順序很重要蛇数,必須與TabBar
中的選項(xiàng)卡的順序相對(duì)應(yīng)!
TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
);
4. 完整例子
import 'package:flutter/material.dart';
void main() {
runApp(TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: Text('Tabs Demo'),
),
body: TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}