一.復(fù)習(xí)上一章
- TabBar 添加 controller 獲取滑動(dòng)監(jiān)聽
class MyButtonWidget extends State<Mypage2>
with SingleTickerProviderStateMixin {
TabController tabController;
@override
void initState() {
// TODO: implement initState
super.initState();
tabController = new TabController(vsync: this, length: 2);
tabController.addListener(() {
print(tabController.index);
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: TabBar(
controller: tabController,
tabs: <Widget>[Tab(text: "熱門"), Tab(text: "推薦")],),),
body: TabBarView(
controller: tabController,
children: <Widget>[]),
),
);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
tabController.dispose();
}
}
- TabController 使用步驟
1、有狀態(tài)組件多繼承 SingleTickerProviderStateMixin
2、在initData中 初始化TabController傳入兩個(gè)參數(shù),固定寫法
3、TabBar 和 TabBarView 都需要配置上 controller。
二.Drawer側(cè)邊欄
在Scaffold組件倆面?zhèn)魅雂rawer 參數(shù)可以定義左側(cè)邊欄,傳入endDrawer可以定義右側(cè)邊欄,側(cè)邊欄默認(rèn)是隱藏的,我們可以通過手指滑動(dòng)顯示側(cè)邊欄,也可以通過點(diǎn)擊按鈕顯示側(cè)邊欄。

image.png
三.DrawerHeader 帶頭部的抽屜
- 常見屬性
- decoration:設(shè)置頂部背景顏色
- child:配置子元素
- padding:內(nèi)邊距
- margin:外邊距
endDrawer: Column(
children: <Widget>[
Expanded(
child: DrawerHeader(
child: Text("右側(cè)邊欄"),
decoration: BoxDecoration(color: Colors.red),
),
),
],
)
四.收起抽屜
- 和退出頁面一樣使用 Navigator.of(context).pop() 關(guān)閉抽屜
drawer: Drawer(child: MyDrawerWidget())
class MyDrawerWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Column(
children: <Widget>[
Container(height: 200),
Text("左側(cè)邊欄"),
RaisedButton(
child: Text("點(diǎn)擊收起側(cè)邊欄"),
onPressed: () {
Navigator.of(context).pop();
},
),
RaisedButton(
child: Text("點(diǎn)擊進(jìn)入搜索頁面"),
onPressed: () {
Navigator.of(context).pop();
Navigator.pushNamed(context, "/search");
},
)
],
);
}
}
注意
- 異常: Navigator 中的context 使用MaterialApp中的context 會(huì)報(bào)錯(cuò)
“Flutter Navigator operation requested with a context that does not include a Navigat”- 解決方法:將 MaterialApp 內(nèi)容再使用 StatelessWeight 或 StatefulWeight 包裹一層,然后使用子組件的context。
-
效果圖
dawer.gif
五.總結(jié)
1、側(cè)邊欄實(shí)現(xiàn)
Scaffold(drawer: Drawer(child: MyDrawerWidget()))
2、關(guān)閉側(cè)邊欄
Navigator.of(context).pop()
