flutter tab頁籤 appbar 下的頁籤
TabBar 、Tab、TabBarView 結合實作
這裡實作的是appbar 下的頁籤
import 'package:flutter/material.dart';
/**
* 有狀态StatefulWidget
* 繼承于 StatefulWidget,通過 State 的 build 方法去建構控件
*/
class TabBarAndTopTab extends StatefulWidget {
通過構造方法傳值
TabBarAndTopTab();
//主要是負責建立state
@override
_DemoStateWidgetState createState() => _DemoStateWidgetState();
}
/**
* 在 State 中,可以動态改變資料
* 在 setState 之後,改變的資料會觸發 Widget 重新建構重新整理
*/
class _DemoStateWidgetState extends State<TabBarAndTopTab>
with SingleTickerProviderStateMixin {
_DemoStateWidgetState();
List tabs = ["首頁", "發現", "我的", "設定"];
//用于控制/監聽Tab菜單切換
//TabBar和TabBarView正是通過同一個controller來實作菜單切換和滑動狀态同步的。
TabController tabController;
@override
void initState() {
///初始化,這個函數在生命周期中隻調用一次
super.initState();
tabController = TabController(length: tabs.length, vsync: this);
}
@override
void didChangeDependencies() {
///在initState之後調 Called when a dependency of this [State] object changes.
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return buildTabScaffold();
}
//通過“bottom”屬性來添加一個導航欄底部tab按鈕組,将要實作的效果如下:
Widget buildTabScaffold() {
return Scaffold(
appBar: AppBar(
title: Text('标題'),
//設定頁籤
bottom: buildTabBar(),
//設定标題居中
centerTitle: true,
),
//設定頁籤對應的page
body: buildBodyView(),
);
}
//當整個頁面dispose時,記得把控制器也dispose掉,釋放記憶體
@override
void dispose() {
tabController.dispose();
super.dispose();
}
buildBodyView() {
//構造 TabBarView
Widget tabBarBodyView = TabBarView(
controller: tabController,
//建立Tab頁
children: tabs.map((e) {
return Container(
alignment: Alignment.center,
child: Text(e, textScaleFactor: 1),
);
}).toList(),
);
return tabBarBodyView;
}
buildTabBar() {
//構造 TabBar
Widget tabBar = TabBar(
//tabs 的長度超出螢幕寬度後,TabBar,是否可滾動
//設定為false tab 将平分寬度,為true tab 将會自适應寬度
isScrollable: false,
//設定tab文字得類型
labelStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
//設定tab選中得顔色
labelColor: Colors.white,
//設定tab未選中得顔色
unselectedLabelColor: Colors.white70,
//設定自定義tab的訓示器,CustomUnderlineTabIndicator
//若不需要自定義,可直接通過
//indicatorColor 設定訓示器顔色
//indicatorWight 設定訓示器厚度
//indicatorPadding
//indicatorSize 設定訓示器大小計算方式
///訓示器大小計算方式,TabBarIndicatorSize.label跟文字等寬,TabBarIndicatorSize.tab跟每個tab等寬
indicatorSize: TabBarIndicatorSize.tab,
//生成Tab菜單
controller: tabController,
//構造Tab集合
tabs: tabs.map((e) => Tab(text: e)).toList());
return tabBar;
}
}