TabBar

在页面上渲染 TabBar 组件,通常配合 Scaffold 组件的 bottomNavigationBar 属性一起使用,用来渲染底部的 TabBar 效果。

注意:

  • TabBar 最好和有状态页面配合使用

  • TabBar 必须指定 TabController 控制器,用来控制 TabBar 的切换

  • 如若不指定 TabController 控制器,也可以使用 DefaultTabController 组件,把 TabBar 组件包裹起来,同时提供需要切换的页面个数即可,代码示例如下:

  1. DefaultTabController(
  2. // 指定需要切换的页面个数
  3. length: tablist.length,
  4. child: Scaffold(
  5. appBar: AppBar(),
  6. // 被 tabbar 控制切换的页面
  7. body: TabBarView(),
  8. // 指定 tab 项
  9. bottomNavigationBar: TabBar(
  10. tabs: tablist
  11. )
  12. ),
  13. )
  • TabController 必须用在拥有 TickerProviderStateMixinSingleTickerProviderStateMixin 特征的类中,因此,必须让 TabController 所在的类实现此特征,代码示例如下:
  1. class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin { }

实现步骤:

  • 创建对应的 Tab 项:
  1. List<Widget> tablist = <Widget>[
  2. Tab(
  3. text: '正在热映',
  4. icon: Icon(Icons.movie),
  5. ),
  6. Tab(
  7. text: '即将上映',
  8. icon: Icon(Icons.movie_filter),
  9. ),
  10. Tab(
  11. text: 'Top250',
  12. icon: Icon(Icons.local_movies),
  13. ),
  14. ];
  • 创建 TabController 对象:
  1. TabController tabCtrl;
  • 在 initState 生命周期函数中,初始化 tabCtrl 对象:
  1. @override
  2. void initState() {
  3. super.initState();
  4. tabCtrl = TabController(vsync: this, length: tablist.length);
  5. }
  • 为 Scaffold 添加 bottomNavigationBar 选项如下:
  1. bottomNavigationBar: Container(
  2. // 设置 tabbar 的背景色
  3. decoration: BoxDecoration(color: Colors.black),
  4. // 设置 tabbar 的高度
  5. height: 50,
  6. // 指定 tabbar 组件
  7. child: TabBar(
  8. // 指定 tabbar 的控制器,必须提供控制器,否则 tabbar 不能正常工作
  9. controller: tabCtrl,
  10. // 设置 tabbar 中文本的样式,注意,height 属性很重要,必须设置为 0,否则文本和图标之间的距离太大,不美观
  11. labelStyle: TextStyle(height: 0, fontSize: 10),
  12. // 设置指示器的颜色
  13. indicatorColor: Colors.red,
  14. // 指定当前 tabbar 总共有几个按钮
  15. tabs: tablist,
  16. ),
  17. )